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: