Few Things to Note When Authoring jQuery Plugin
I was spending my time on authoring jQuery plugin, in past few days. This is the very first jQuery plugin I have worked on, which is based on jQuery core library, version 1.3.2. In a nutshell, I have adopted my previous work, Agotcha! to come out with a simple shoutbox widget, yet it’s supported by jQuery library. The main objective of this work is to challenge myself and therefore, having deeper understanding on how jQuery works.
Well, after I have got this plugin done, from what I have experienced, here are few important things I personally felt that every developer should pay attention when authoring a jQuery plugin.
1) Passing jQuery object to Anonymous function
First and foremost, before you start putting any code of yours, it’s always a good idea to pass the jQuery object to an anonymous function, as suggested in jQuery’s Plugins/Authoring page (and also mentioned in other developers’ blogs). If you have been coding jQuery before, I believe most of the time you will use jQuery’s alias object- “$” the dollar sign for calling a method/function. Why to do so? something you need to keep in mind is, there are thousands of libraries are available and can be found online and they maybe using the same “$” object, the well-known library is Prototype. So to avoid any object conflicts, you should always wrap jQuery object and pass it to an anonymous function, so that you are allowed to use the “$” alias without worrying conflict with other libraries, especially when a developer he or she is using more than one JavaScript library. Here how it does look like:
(function($){ //your code is going from here... }) (jQuery);
As you may have already known, this anonymous function will be invoked immediately once the page is loaded, by passing ‘jQuery’ object and assigned to a ‘$’ dollar sign, then only proceed to your own code. By using this trick, you can always use $ object within the function without worrying the conflicts.
2) Methods or Functions?
If you have read the jQuery’s Plugins/Authoring page, you may have already known that any methods should be attached to jQuery.fn object; and all functions to the jQuery object. Well, what all these mean to us? Most of the articles or tutorials have done a good job and also shown the way of authoring a jQuery plugin, but most of the time, it seldom mentions when and why we should use that in our own plugins and I do believe, some of the developers are confused with these when trying to get started with jQuery plugin development.
When to use method and attach it to jQuery.fn or $.fn?
From my understanding, you will only attach a method to jQuery.fn when the same method is being used more than one time, and more importantly, it’s attached to jQuery.fn when you wanted to use it for ‘chaining’ purpose. In other words, you should always return it (jQuery object) once the process is done and to allow it’s used together with the jQuery’s methods from the core library. For instance, you wanted to add css after your method was called. All we do is put it as chaining pattern:
$.fn.myOwnMethod = function(){ return this.each(function(){ // 'this' in each() function is always referred to current HTML's element object... $(this).html("this is my text.."); }); }; $(function(){ $("div#myId").myOwnMethod().css('background-color', '#ccccff'); });
From the snippet above, you’re applying your own method (myOwnMethod) to an HTML’s div element with its id, ‘myId’ by inserting text and then chained it with jQuery’s css() method and set the div’s background colour as ‘#ccccff’. The core concept behind is, or something you must always keep in mind is the ‘this’ object:
i) ‘this’ tied with each() method, this.each():
– The word, ‘this’ here is the jQuery’s object, as in the ‘$’ dollar sign object, which is being used to call the each() method from the core library.
ii) ‘this’ inside each() method:
- The ‘this’ object here is always referred to the current HTML’s element object. In this example is, the div element with ‘myId’.
With this solid concept in mind, you are able to create any methods of yours that will be used for chaining with current jQuery’s core methods and utilities.
How about the ‘functions’?
Personally, I feel that creating functions is much more easier than methods, as what I have explained, previously. Functions in jQuery are basically created and tied directly with jQuery’s object: ‘jQuery’ and its alias, ‘$’ dollar sign. In other words, whenever you need it, just call it directly via jQuery’s object. Most of the time, it’s also called as ‘public method’ which will be directly called for getting a result. The way we define the function is as follows:
$.myOwnFunction = function(){ //put your code here... }; //to call it $.myOwnFunction();
Pretty straight-forward, right? What you need to do is putting everything inside ‘myOwnFunction’ function that attached to jQuery object and then call it straight via its object.
Which one should be used?
To me, it really depends on what you are going to do with your plugin. You may just either use method or function, or even both of them in your jQuery plugin. But, always ask yourself what is the purpose of creating this method/function? Would it be used for chaining? With this concept in your mind, you are able to create jQuery plugins, on the fly.
3) Using jQuery, $.extend()
You must always understand and clear with a method or function you are going to use, before you’re getting frustrated of it. So, if you do not know what is jQuery’s extend() used for, here you go. Most of the time, you will need $.extend() to extend jQuery’s object. Say, I have already created a function, named as ‘myOwnFunction’ and I wanted to extend it with an object-literal and to allow me to access the properties from the object-literal, via ‘myOwnFunction’. Here is what I will do:
$.myOwnFunction = function(){ //my code here... }; //extend the function and make it as 'object function' $.myOwnFunction = $.extend( $.myOwnFunction, { name1: value1, func1: function(){ //some block code... }, //more functions/properties here... } );
So, what was just happening? By using $.extend(), I have actually made the ‘myOwnFunction’ as an object, too! That means, I can now not only call the function via $ object, and at the same time, I can ‘extend’ the function to play as object as well, in order to access the properties/ functions from the object-literal.
Sometimes, you may want to allow user inputs options apart from the default settings in your plugin. Here, $.extend() will take the place, again. For instance:
$.myOwnFunction = function( userOptions ){ //the default settings... myDefaultSetting = { name1 : value1, nameN : valueN }; //merge it with default or, overwrite when different value assigned... if( userOptions ){ myDefaultSetting = $.extend( myDefaultSetting, userOptions ); } };
The example above is to allow users provide the options apart from using yours default values. Don’t you think that it will be more user-friendly plugin, huh? Give applause to jQuery!
4) The $(‘id’).find() method
Last but not least, one more important thing we should take note is always looking for the correct and matched to the right HTML element. From what I have experienced, sometimes we might forget or overlook to look up the correct HTML elements. It will be a pitfall if we never look for an HTML element in detailed, although everything seems working pretty fine. Well, just consider of this example:
$("div>ul").css("background-color", "blue"); $("ul>li").css("background-color", "pink");
From the code, everything seems like working pretty well, where we have tried to set the respective background colours to the ‘ul’ tag and its ‘li’ in div element, whereas, blue and pink colours. Yet, if you try to duplicate the same div element with ‘ul’ tag resides in it, and then run the code again you will see that, it will apply to all ‘ul’ elements! Think further a little, how about if the developers out there are using your plugin, but it ruins the whole layout in case they are using ‘ul’ in the div element, too!
So, whenever possible, try to use jQuery’s find() method to look up more specific HTML element. This will avoid the problem happening as I mentioned just now. OK, we tweak the code a little as such:
$("div#myId").find("ul").css("background-color", "#ccccff"); $("div#myId").find("ul>li").css("background-color", "pink");
Now, we are able to look for more specific HTML element without affecting user’s interface. If you are putting the code in $.each() function, always use ‘this’ instead since it’s always referred to the current HTML element’s object. The benefit is, when you want to change the div’s id, you do not need to change it in everything single line of code and therefore, save your time from there.
Hope this post will help someone who is going to author his/her own jQuery plugin(s).
Related posts:
