开发者

Understanding jQuery plugin development pattern

According to the jQuery plugin authoring guidelines, a basic plugin structure would look like this:

(function($){

  $.fn.myPlugin = function( options ) {  

    return this.each(function() {

      // Do something...

    });
  };
})( jQuery );

Yet I've seen the following pattern in several jQuery plugins I've inspected:

(function($){
        $.extend($.开发者_如何学Gofn, {
            myPlugin: function( options ) {

                $(this).each( function() {
                    // Do something
                });
        },
    })
})(jQuery);

Can someone explain the second approach- What is $.extend(... and the object-notation all about?

Thanks-


These two are basically accomplishing the same task, but in a slightly different manner.

$.fn.myPlugin = … is directly assigning the function to the place you want it in the jQuery namespace.

$.extend($.fn, {myPlugin:… is extending the $.fn object with the object specified as the second parameter. In this case, the object simply contains a single property, myPlugin, which is the function to add.

You can use either structure, although I personally find the first a bit cleaner.


The $.extend function is used to:

Merge the contents of two or more objects together into the first object.

So this:

$.extend($.fn, { ... });

Is just merging the contents of the object literal into $.fn. Using $.extend like this just really just another way of doing the normal/standard assignment:

$.fn.myPlugin = ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜