The best way to write a jQuery plugin - If there is such a way?

Posted by Nick Lowman on Stack Overflow See other posts from Stack Overflow or by Nick Lowman
Published on 2010-06-02T11:45:19Z Indexed on 2010/06/02 14:34 UTC
Read the original article Hit count: 218

Filed under:
|

There are quite a few ways to write plugins i.e. here's a nice example and what I've seen quite a lot of lately is the following code pattern and it's used by Doug Neiner here;

(function($){
   $.formatLink = function(el, options){
    var base = this;
    base.$el = $(el);
    base.el = el;
    base.$el.data("formatLink", base);
    base.init = function(){
       base.options = $.extend({}, $.formatLink.defaultOptions, options); 
       //code here
    }                 
    base.init();
   };

   $.formatLink.defaultOptions = { };

   $.fn.formatLink = function(options){
      return this.each(function(){
       (new $.formatLink(this, options));
      });
   };
})(jQuery);

So, can anyone tell me the benefits of using the pattern above rather than the one below. I can't see the point in calling the $.extend function for every element in the jQuery stack (above), where the example below only does this once and then works on the stack.

To test it I created two plugins, using both patterns, which applied styles to about 5000 li elements and the code below took about 1 second whereas the pattern above took about 1.3 seconds.

(function($){
   $.fn.formatLink = function(options){
       var options = $.extend({}, $.fn.formatLink.defaultOptions, options || {});

       return this.each(function(){
        //code here
       });
    });

$.fn.formatLink.defaultOptions ={}
})(jQuery);

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery