views:

66

answers:

1

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);
A: 

I know Doug used this format when writing Anything Slider, I think it was done to expose internal functions and make it easier to call them after an addon has been initialized. For example in Anything Slider you can go to a particular slide two ways:

  1. Use $('.anythingSlider').anythingSlider(2); which is intented for external links. But this method actually uses the method below to perform the action.
  2. A second way, which shows how you can access the sub function through the data is done like this: $('.anythingSlider').data('AnythingSlider').gotoPage(2);

Maybe there are easier/better ways, but I would think the author has the best explaination/reasoning for this method. So @Doug Neiner (if that works), give us an idea :)

fudgey
@fudgey - your absolutely right. I found this example on his site about custom events http://fuelyourcoding.com/jquery-custom-events-they-will-rock-your-world and after reading through his code I saw why he used the pattern he did. It made complete sense. I think the answer to my question is to use the plugin pattern which is most relative to the task I'm doing.
Nick Lowman
Also found this which is pretty helpful http://fuelyourcoding.com/jquery-plugin-design-patterns-part-i/
Nick Lowman