jquery plugin $.extend

≯℡__Kan透↙ 提交于 2019-12-06 13:55:41

UPDATE

When you are doing multiple operations involving more than one selector, you have to decide what makes the most sense. If one selector is the primary focus, but effects other items as well, write it like a plugin, and return the primary result set like this:

$.fn.myAction = function(secondarySelector){
      return this.each(function(){
          $(this).css('display', 'block');
          $(secondarySelector).hide();
      });
};

// Use:
// $(primarySelector).myAction(secondarySelector);
$("#id").myAction(".address"); // Chain continues after action

If the selectors are all equal in importance, then simply create a function that does not return anything or returns true / false depending on success.

Another way to structure the code:

The extend method is used in other OOP frameworks and as you have shown, can be used with jQuery as well. What you will find, however, is many jQuery developers opt for the shorter more obvious syntax like this:

(function($){

    // The if statement allows the file to be used with
    // other files that use the same shared namespace
    if(!$.Namespace){
        $.Namespace = { };
    };

    $.Namespace.Constructor = function( params ){
       ... code ...
    };

    // And for the wrapper sets ($.fn):
    $.fn.functionName = function(opts){
       return this.each(function(){
          ... code ...
       });
    };

})(jQuery);

You can return whatever you like in the second instance. Forexample think of $.each() versus $.get(). However, if i were you i would avoid using this as a function namespace - it can lead to pollution. Instead you shoudl reserve this for add your own namespace under the jquery namespace like:

(function($){
    $.extend({
        myNamspace : {
          functionName: function(){
            // return whatever
          }
        }
    }});
})(jQuery);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!