Jul/091
How to use object oriented programming with jQuery
Unlike many other JavaScript frameworks jQuery provides few object oriented programming utilities, since JavaScript is all ready object oriented there is no need to. That being said, the means of using object oriented programming with jQuery are limited by some aspects of jQuery it’s self. jQuery is really a function that returns a jQuery object or an array of jQuery objects. That can be confusing since there is both a jQuery function and a jQuery object. Due to this fact there is nothing exactly to sub-class before the jQuery function has returned a jQuery object. What you can do is define a JavaScript object that specifies your own member variables and functions. Once you retrieve a jQuery object, you can use the jQuery.extend() function to copy the members of your object to the returned jQuery object.
Here is a simple example to illustrate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title> Object Oriented jQuery </title> <script src="jquery-1.3.2.js"></script> <script language="JavaScript"> var hideMeShowMe = { hideME: function(){ this.data('baseDisplay', this.css('display')); this.css('display', 'none'); }, showMe: function(){ this.css('display', this.data('baseDisplay')); } }; jQuery( function(){ var pageElement = jQuery('#myElement'); jQuery.extend(pageElement, hideMeShowMe); pageElement.hideME(); } ); </script> </head> <body> <div id="myElement"> This is hideable </div> </body> </html> |
This allows you to extend a single jQuery object with your object’s functionality. There is another approach that you could take which is to use the jQuery.fn.endtend function. That function will cause all of your objects members to be copied to all jQuery objects returned by the jQuery function, that is how plugins work. Which approach you use depends on what you are trying to do, if you are going to make one kind of control that has a specific purpose, it makes sense to use the approach I cover here instead of adding it as a plugin. If you are going to add functionality that will be used more broadly then it makes more sense to add that functionality as a plugin.
This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:
Jun/091
jQuery makes me go hmmm
So I was busy looking into the ways to use jQuery in a prototype based object oriented fashion and was having a devil of a time geting it to work. I eventually turned to Goolge for help and I discovered this thread which is a discussion of sub-classing the jQuery object. It is mostly a back and forth between John Resig and Nate Cavanaugh covering Nate’s attempts at sub-classing jQuery. The long and short of the discussion is that jQuery has so many references to the global jQuery object that it cannot be cleanly sub-classed
So my initial concept was to subclass the jQuery object in my own objects to make new JavaScript objects with all of the functions of jQuery as well as my additions, but that is not going to work. That being said jQuery has a number of methods of adding objects and functions to jQuery; which is basically how plugins are developed. I will explore extending the jQuery and JQuery.fn objects with my own objects next.
This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:
Jun/092
jQuery is object oriented
When I first looked at the jQuery frame work, a few years ago I immediately discounted it as a viable framework. My whole reason for that decision was that it did not add a traditional class based object oriented layer. A little more than a year later I started reading about jQuery’s speed and small size. I decided that I would give it a full chance and start using it on a few projects. I found many advantages to jQuery but was still turned off by its apparent lack of object oriented features. I wrote a blog post to that affect and the response was rather vehement as many took my statement that “you should not choose jQuery if you wanted an object oriented framework,” to be a condemnation of jQuery. Some statements though were rather enlightening, specifically ones that pointed out that JavaScript is all ready object oriented and does not need a framework to make it so.
That last point was interesting as I all ready knew that JavaScript was an object oriented language, but since it did not do objects like I learned to do them in C++ and PHP it sort of slid under my obvious filter. Suddenly I realized I need to look into how JavaScript was object oriented, started learning about Prototype-based programming, and learn how JavaScript uses it. This began a cascade of shifting thought about how to program in JavaScript and how to use jQuery. So now I am exploring how to create objects in a JavaScript centric way and how to do object oriented jQuery development.
Some things to take away from this little post is that JavaScript is object orented, JavaScript is a prototype based language and jQuery is a prototype centric JavaScript library.
This is part of my ongoing series of posts exploring the use of jQuery and object oriented JavaScripts, you might be interested in these posts as well:
Feb/092
The one real reason to not use JQuery
JQuery is a very nice for DOM manipulation and access. As I mentioned in my last post, JQuery uses standard CSS selectors by default which is very nice. You can create fairly complex actions with very few lines of code.
What it does not have that MooTools and Prototype.js both have is a rich set of object oriented oriented development functions. JQuery is ver DOM centric and does not have much in the way of utilities that are not directly related to accessing and manipulating the DOM. You can greatly extend the functions of elements in the DOM or add elements to the DOM. Once you are working with pure JavaScript objects JQuery does not have much to offer. This begins to become eveident right away when compairing the core sections of both MooTools and JQuery. In JQuery’s core the first things are DOM element access and creation functions; where MooTools’ core is all JavaScript and OO featrues. The Extend function is a good example, extend is a core componenet of MooTools and a Utility in Jquery.
Beyond that the true reason for using MooTools is the the object oriented programming features. The Function and Class features of MooTools are simply not implimented in JQuery. This makes taking advantage of Encapsulation, Inheritance and Polymorphism very difficult with JQuery, which pretty much leaves all of the work of implementation of those features up to you.
That being said you can use the JQuery’s noConflict() function and use both MooTools and JQuery. I have not explored how the two will play together when writing object oriented code with Mootools functions and accessing the DOM with JQuery, but I do plan to give this a try in the near future.
Feb/080
The MooTools Ajax class, the easiest path to dynamic content.
The guys over at MooTools created a whole series of remote server JavaScript classes that make it easier to communicate asynchronously with the server. One of the easiest is the object found in MooTool’s Ajax.js file aptly named the Ajax object.
The Ajax object is not really designed for complex handling of the response from the server; it is really a down and dirty go here and put what you find there in this element kind of object. So the basic syntax is:
1
2
3
4
5 <div id="showTime"></div>
<script language="JavaScript">&gr;
var myAjax = new Ajax('http://www.sweetvision.com/servertime.php', {update: $('showTime')});
myAjax.request();
</script>&gr;
In the preceding code we are creating a new Ajax object that accesses the URL ‘http://www.sweetvision.com/servertime.php’ and what ever is retuned by that URL is injected into the DIV identified by “showTime”. Request() is the member function of the Ajax object that actually sends the request, the object handles the rest.
Another thing that the Ajax object simplifies for you is sending the contents of a form asynchronously. If you have included Ajax in your download of MooTools then any time you reference a form with $(‘formID’) it automatically has an Ajax object in it and you can use $(‘formID’).send() to send the form to the server. Send() takes the same options that the Ajax() constructor takes so you can use update: just like in the example above to display the results of your form submission on your page. You also might want to pass in a function to the onComplete event and hide the form when the ajax request is completed.
Dec/070
Using setTimeout in objects with Mootools
Often you wish to use setTimeout to call a function in the objects you are creating with MooTools or perhaps even more often you would like to pass parameters into your set time out calls. Well, the MooTools framework has given us a plethora of tools to do all of this and more. In this post I will discuss how you can pass parameters with setTimeout (Well, not really ‘into’ setTimeout, but a better way to get the same result.) and call your functions, delayed and recurring, from your objects created with the MooTools class function.
Closures and bind()
The first problem we tend to encounter the first time we try to do this is that when our member function gets called by setTimeout we get a bunch of errors that our variables are undefined. This problem is caused by JavaScript’s lack of closures which means that there is not hard binding between the function and the object that it is declared in. If you do a little debugging you will discover that the this operator is pointing at the window object not your object. The reason for that is that setTimeout causes the function to be called by the window object and in JavaScript this points to the calling scope.
Because the issue of closures is a problem in many cases when using JavaScript MooTools came up with a generic solution to the problem called bind. The bind() method is a part of the functions.js, found in the Native collection of MooTools functions. Their docs on bind can be found here. The Bind() member function will allow you to bind the this operator to any object you choose, which often will be the this of the object you define it in, but could be any object in the DOM. You can use bind when you call set time out like setTimeout(this.myfunction.bind(this), 1000) to call functions in your object delayed and have still have the this operator point at what you expect it to. That having been said, MooTools has two other functions to help you with delayed and recurring function calls in a much more efficient manner.
Delayed and Recurring calls
As this is an article about setTimeout, you are most likely unconcerned with what closures are and are just wanting your delayed function or recurring/polling/periodic function to work. If so, this is the section for you! The MooTools library provides two functions for calling functions, either delayed or periodically. They are, not surprisingly, called ‘delay’ and ‘periodical’. You use delay when you want a function to execute in so many seconds or periodical when you want a function to execute every so many seconds. Both of these functions return their timer ID and can be stopped by passing that into the $clear() function.
Delay example:
delay_demo = new Class({
initialize: function(dateString){
this.count = 0;
this.delayTimer = this.updateCount.delay(1000, this);
},
updateCount: function(){
this.count++;
}
});
periodical example:
periodical_demo = new Class({
initialize: function(dateString){
this.count = 0;
this.startTimer();
},
updateCount: function(){
this.count++;
},
stopTimer: function(){
$clear(this.periodicalTimer);
},
startTimer: function(){
this.periodicalTimer = this.updateCount.periodical(1000, this);
}
});
Passing Parameters
Another important feature of bind, delay and periodical is that they will allow you to pass parameters or arguments to the functions they call. Passing arguments to a function called with bind, delay or periodical is as easy as adding a second parameter for bind and, in the case of delay and periodical, a third parameter that is an array of parameter values; e.g., myfunction.periodical(1000, this, [ParamVal1, ParamVal2, "strParamVal3"]) or myfunction.bind(this, [ParamVal1, ParamVal2, "strParamVal3"]).
Common Errors Encountered
There are some situations where you might get an error that does not really explain what the problem is. I have run into two when working with these functions. The first is the “too much recursion” error from Firefox or FireBug. This error indicates that you have used the parenthesis in a place you should not have, an example is using myfunction().delay(1000, this) instead of myfunction.delay(1000, this). The other is having a function that calls periodical that calls its self, which will cause an exponential increase in the number of calls to that function until your browser locks up.
periodical lockup example:
periodical_demo = new Class({
initialize: function(dateString){
this.count = 0;
this.startTimer();
},
updateCount: function(){
this.count++;
},
stopTimer: function(){
$clear(this.periodicalTimer);
},
startTimer: function(){
this.periodicalTimer = this.startTimer.periodical(1000, this); //Note calling startTimer from inside startTimer with periodical is very bad.
}
});
MooTools has neatly provided simple ways to accomplish all of the tasks we would normally use setTimeout for.
Apr/072
Color Picker v1.0.1 Released
I have done some debugging of the color picker in Opera. There were problems with many of the Canvas functions needed in Opera 9.0, but things work beautifully in Opera 9.1.
I have also done some testing with Firefox 1.5 and Safari. Things do not work at all well in FireFox 1.5 as it is missing some key functionality and I am not planning on making it work in old versions of FireFox given 2.0’s wide spread install base.
Safari is close to working but I am having specific problems with the context.createLinearGradient() function in my version of Safari. Even though; when I look at the context it says that the createLinearGradient function exists it keeps returning undefined for me when I call it. If there are any Mac/Safari gurus out there that can see why this might be happening I would love to hear from you.
The Color Picker now supports FireFox 2.0, IE 7.0, and Opera 9.10.
See examples and download from the Color Picker Project Page.
Apr/070
Complete JavaScript Color Picker
Welcome to the final installation of my JavaScript based Color Picker series. I have made a lot of changes to the color picker since my last installment.
Layout
I found some major problems based on the document type with the way I was laying out elements in the color picker dialog, so I decided that it needed to use the lowest common denominator in order to work reliably, so it is laid out with, *gasp* tables.
Sizing
After adding the support for the Canvas element I decided to add options to size the HueBar and the SV Box.
1
2
3
4
5
6
7
8
9
10 if(this.Options.hueBarWidth){
this.HueBar.setStyle("width", this.Options.hueBarWidth);
}else{
this.HueBar.setStyle("width", "30");
}
if(this.Options.hueBarHeight){
this.HueBar.setStyle("height", this.Options.hueBarHeight);
}else{
this.HueBar.setStyle("height", "360");
}
Options
I added the ability to pass in an Options object that gives the ability to customize many parts of the Color Picker.
1
2
3
4 this.Options = {};
if(objOptions){
this.Options = objOptions;
}
Open/Close
I created Open and Close member functions on the color picker object its self.
1
2
3
4
5
6 open: function (){
this.Container.setStyle("display", "block");
},
close: function (){
this.Container.setStyle("display", "none");
}
You can download the full source from the JavaScript Color Picker project page.
Mar/071
Enhancing the JavaScript Color Picker with the Canvas element
With the previous implementation of the Color Picker I used div elements to make the individual “pixels” of the color picker, attaching an event to each div element. This incurs quite a bit of overhead, causing the color picker to perform poorly especially on slower systems. The most obvious way to create something like a color picker efficiently is to use the Canvas element.
First, I needed to detect whether the browser supports the Canvas element. I do that by creating a Canvas element and then seeing if it will return a context like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 testcanvas = document.createElement("canvas");
if(testcanvas.getContext){
this.supportsCanvas = true;
delete testelement;
}else{
this.supportsCanvas = false;
delete testelement;
}
Next, in the constructor I needed to create Canvas elements instead of div containers for the Hue Bar and SV Box. Here is a snip of code for the Hue bar:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 if(this.supportsCanvas){
//create the canvas Saturation Value Box.
this.HueBar = new Element("canvas");
this.HueBar.setStyle("cssFloat", "left");
this.HueBar.setStyle("styleFloat", "left");
this.HueBar.setStyle("margin-right", "5px");
this.HueBar.width=30;
this.HueBar.height=360;
this.HueBar.addEvent("click", this.setCurrentHue.bind(this));
this.Container.appendChild(this.HueBar);
}else{
//create the container for the hue bar.
this.HueBar = new Element("div");
this.HueBar.setStyle("width", "30px");
this.HueBar.setStyle("cssFloat", "left");
this.HueBar.setStyle("styleFloat", "left");
this.HueBar.setStyle("margin-right", "5px");
this.Container.appendChild(this.HueBar);
}
Note: in the case of using the Canvas element, the events are attached to the canvas instead of child elements.
The next difference is in the drawHueBar and drawSVBox functions. In the drawHueBar function, we figure out the multiplier we will need for get steps between 0 and 360 for the height of our bar. Create a new color that is at hue 0 and full saturation and brightness. Get a 2d context to the HueBar canvas element. Iterate over the height of the HueBar. Set the hue for the current position on the HueBar. Get the Hex color string for the new Hue. Set the Canvas Context’s fill style to the Hex color string. Then, fill a Rect that is as wide as the HueBar and 1 pixel tall with that color. Rinse and repeat until we have iterated the whole HueBar.
Here is a snip of code from the drawHueBar function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 drawHueBar: function (){
if(this.supportsCanvas){
hSteps = 360 / this.HueBar.height;
hColor = new Color([0,100,100], 'hsb');
myCTX = this.HueBar.getContext('2d');
strhHex = "";
for(hi = this.HueBar.height; hi > 0; hi--){
hColor.changeHue(hi*hSteps);
strhHex = hColor.rgbToHex();
myCTX.fillStyle = strhHex;
myCTX.fillRect(0, this.HueBar.height-hi, this.HueBar.width, 1);
}
}else{
hsvColor = new Color([0,100,100], 'hsb');
fcoDiv = new Element("div");
fcoDiv.setStyle("width","30px");
fcoDiv.setStyle("height","1px");
...
}
}
For the SVBox, it is mostly the same, changing the Brightness in the loop instead of the Hue. I make use of the Canvas element’s gradient fill functions to simplify the work. Inside the loop over the height of the SVBox, we create a new gradient that goes from the left side of the SVBox to the Right. We add a color stop to the linear Gradient that is just a gray value between white and black based on the current position in the height of the SVBox. Then we add a color stop that is based on the current iterations HSV value. Set the Canvas context’s fill style to the gradient and then fill one row of the SVBox.
myLinearGrad = myCTX.createLinearGradient(0, 0, this.SVBox.width, 0);
myLinearGrad.addColorStop(0, "rgb("+vi+","+vi+","+vi+")");
myLinearGrad.addColorStop(1, strsvHex);
myCTX.fillStyle = myLinearGrad;
In the case of using the Canvas element, the UpdateSVBox code does the exact same thing as the drawSVBox.
Getting the color clicked on is a little different and we need to deal with the DOM a little more. In order to get the color clicked on we need to call the getImageData(X, Y) function from a Canvas context object. The issue with that is the event.ClientX and the event.ClientY that is passed in is in the window coordinate space, not our canvas elements coordinate space, so we have to translate. In the event call back functions we need to do the following to get the colors from the Canvas elements. Get a 2d context to the Canvas element. Call the MooTools Element.getCoordinates() function to get the left and top of the canvas in the Window coordinate space. Then, for each axis subtract the Canvases left or top from the clientX or clientY then add the window.scrollX or window.scrollY to deal with the page being scrolled if it is. Pass the resulting X and Y into the context’s getImageData function to get an imageData object for the pixel. The imageData.data array will contain the RGB values for the pixel.
myCTX = this.HueBar.getContext('2d');
hBoxCoords = this.HueBar.getCoordinates();
myImageData = myCTX.getImageData(e.clientX - hBoxCoords.left + window.scrollX, e.clientY - hBoxCoords.top + window.scrollY, 1, 1);
CurHueColor = new Color([myImageData.data[0], myImageData.data[1], myImageData.data[2]]);
With this update the Color Picker is significantly faster with a capital ‘S’, unless you are using IE and then it is just as slow as before. (A fact which totally burns my britches, since IE has such a large portion of the browser market share. I will have to figure out something to do about that in the IE case.)
See the code for the whole Canvas enhanced ColorPicker class
Canvas based Color Picker example
This code was tested in IE 7 and Firefox 2. The Canvas element was not added to Firefox until version 2, no Canvas element in IE.
Mar/071
Writing a Color Picker in JavaScript
I thought it would be cool to have a color picker for a number of dynamic web applications, so I decided to go about making one. What follows here is the basics of the first iteration of a color picker. This is by no means the most efficient that it could be, certainly not for browsers that support the canvas element. This does cover the basic ideas of creating a color picker and provides a good base to build on.
I decided to use MooTools for their Class, Element and Color objects. The Class object and functions are invaluable for writing object oriented JavaScript. The Element object is a great time saver for dealing with DOM Elements and the Color object has all the functionality built in for dealing with HSV (HSB in MooTools).
Some tips that I came across:
In general, I try to create an element once and then clone it when I need many of the same element. One thing that I ran into, that I did not know, is that the DOM cloneNode does not clone events, nor does the MooTools Element.clone() member function. As a result, you have to attach events to each cloned element.
MooTools does not encapsulate all differences between Mozilla-based browsers and IE. Specifically, I ran into this with the event object that is passed into my call back functions. In FireFox, the element clicked is event.target and in IE it is event.srcElement. I am not dissing MooTools there, I have not looked to see if there is even a way for them to deal with that difference seamlessly.
The MooTools documentation on the Color object does not specify the ranges it uses for HSV or RGB. Not all people will know that HSV ranges are different that RGB; specifically, in HSV, hue has a rage from 0 – 360 and both Saturation and Value have a range of 0 – 100%.
Another difference between IE and other standards-based browsers to make note of is the JavaScript notations for float, since float is a reserved word in JavaScript there needs to be a different name for the CSS property. The standard is cssFloat and the Microsoft/IE way is styleFloat.
Ok, now on to the code.
One of the first things I did here is add three members to the MooTools Color class. The MooTools Color class’s setHue, setSaturation and setBrightness functions return a clone of the color object with the new color set. As the color picker’s code will be changing colors over a thousand times per click on the Hue bar I would rather not incur the cost of the clone. Below is the code to add three member functions (changeHue, changeSaturation, changeBrightness) to the color class that change the color values of the color object and return nothing.
The Color Picker consists of a number of elements to facilitate the visual selection of color. On the left is the Hue Bar, which displays all 360 hues at full Value(Brightness) and Saturation, clicking on a Hue will update the SV Box. Just to the right of the Hue bar is the SV Box (Saturation Value Box). The SV Box displays the range of Saturation and Value for a given Hue. In this example we only display a sub set of the Saturation Value combinations that are possible for performance reasons. Hovering over a “Pixel” in the SV Box will display that color in the Preview box and clicking a “Pixel” will set that as the Color Pickers current color, update the Selected color box as well as the HSV and RGB text boxes. To the right of the SV Box is the Selected Color, Preview Color, HSV text boxes, RGB text boxes and the Ok and Cancel buttons. Changing any value in the HSV or RGB text boxes will update the Selected color and the respective color text boxes it the other color space. Clicking the Ok and Cancel buttons will call the associated Ok and Cancel functions, if no Ok or Cancel call back functions have been specified nothing will happen.
The code in the following link is commented so you should be able to follow everything that is going on in the class.
This code has been tested in IE 7 and FireFox 2, if you encounter any issues in other browsers I would be interested in hearing about them especially if you have a solution as well.