admin管理员组

文章数量:1389768

According to the developer documentation jquery plugins are supposed to have only one namespace for all functions they make available. Which is straight forward as long as you only expose a single function per context (static/element).

(function($){

    var

    state_a = 0,

    $.myplugin = function(in_options) {
      // static
      return this;
    }

    $.fn.myplugin = function(in_options) {
      // element
      return this;
    }

})(jQuery);

This makes calls like this possible:

$("elem").myplugin(options);
jQuery.myplugin(options);

What's the best approach if you have more than one function and need to share state? I would like to call into my plugin like this:

$("elem").myplugin.start(options);
$("elem").myplugin.stop();
jQuery.myplugin.start(options);
jQuery.myplugin.stop();

According to the developer documentation jquery plugins are supposed to have only one namespace for all functions they make available. Which is straight forward as long as you only expose a single function per context (static/element).

(function($){

    var

    state_a = 0,

    $.myplugin = function(in_options) {
      // static
      return this;
    }

    $.fn.myplugin = function(in_options) {
      // element
      return this;
    }

})(jQuery);

This makes calls like this possible:

$("elem").myplugin(options);
jQuery.myplugin(options);

What's the best approach if you have more than one function and need to share state? I would like to call into my plugin like this:

$("elem").myplugin.start(options);
$("elem").myplugin.stop();
jQuery.myplugin.start(options);
jQuery.myplugin.stop();
Share Improve this question asked Apr 12, 2010 at 18:43 tcurdttcurdt 15.9k10 gold badges62 silver badges74 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

I've used arguments.callee before:

(function ($) {
    $.fn.pagination = function (options) {
        var defaults = {
        };
        options = $.extend(defaults, options);

        var object = $(this);

        arguments.callee.updatePaging = function () {
            //do stuff
        };
    });

Then, on your page:

    var pagination = $("#pagination");
    pagination.pagination();
    pagination.pagination.updatePaging();

jQuery plugins tend to use a string parameter for different functions:

$(...).myplugin('start', options);
$(...).myplugin('stop');

I can't think of an easy way to use the syntax you would like to use, since having an extra property inbetween will make this point to something else than the jQuery object with the selected elements. Personally I find using a string parameter to pletely change what the function does somewhat ugly too. $(...).myplugin().function() would be doable, but likely not as efficiently as just using that string parameter.

This is explained well in the docs: http://docs.jquery./Plugins/Authoring#Namespacing

本文标签: javascriptjquery plugin with multiple functionsStack Overflow