jquery plugin $.extend

2019-05-24 18:51发布

问题:

if i extend the jquery fn(like $.fn.extend) i write my plugin:

(function($){
    $.fn.extend({
        functionName : function(){
             //function returns
             return this.each(function(){
                  $(this).append("<div>text</div>");
             });
        }
    });
})(jQuery);

when i want to extend jQuery namespace i write it like this:

(function($){
    $.extend({
        functionName : function(){
             //function returns

        }
    });
})(jQuery);

what i don't know is how to write the 'return' in this case

回答1:

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


回答2:

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