开发者

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

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开发者_StackOverflow中文版(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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜