Jquery plugin with multiple functions

According to jquery developer documentation, plugins should have only one namespace for all the functions they provide. This is straightforward if you use only one function for each 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:

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

What is the best approach if you have more than one function and need to share the state? I would like to call my plugin as follows:

$("elem").myplugin.start(options);
$("elem").myplugin.stop();
jQuery.myplugin.start(options);
jQuery.myplugin.stop();
+3
source share
3 answers

I 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();
+5
source

JQuery plugins usually use a string parameter for different functions:

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

, , inbetween this , jQuery . , , . $(...).myplugin().function() , , .

+1

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

0
source

Source: https://habr.com/ru/post/1740813/


All Articles