具有多种功能的jquery插件 [英] jquery plugin with multiple functions

查看:106
本文介绍了具有多种功能的jquery插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据开发人员文档,jquery插件应该只有一个命名空间用于它们提供的所有功能。只要你只为每个上下文公开一个函数(static / element),这是直截了当的。

 (function($) {

var

state_a = 0,

$ .myplugin = function(in_options){
// static
返回此;
}

$ .fn.myplugin = function(in_options){
//元素
返回此;
}

})(jQuery);

这使得这样的调用成为可能:



<$ 。p $ p> $( ELEM)为myplugin(选项);
jQuery.myplugin(options);

如果您有多个功能且需要共享状态,最佳方法是什么?我想这样调用我的插件:

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


解决方案

我之前使用过arguments.callee:

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

var object = $(this);

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

然后,在您的页面上:

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


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

解决方案

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插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆