jQuery插件中的公共函数

Dan*_*iel 33 ajax jquery preloader

我喜欢jQuery插件架构,但是,当我想要保留对插件实例的引用以便稍后在我的代码中访问属性或方法时,我发现它令人沮丧(可能是由于我对我缺乏了解).

编辑:我想澄清我真正想要做的是保留对插件中使用的方法和属性的引用,以便我以后可以使用它们

让我们以AJAX加载图标为例.在更传统的OOP环境中,我可以这样做:

var myIcon = new AJAXIcon();
myIcon.start();
//some stuff
myIcon.stop();
Run Code Online (Sandbox Code Playgroud)

我的对象的方法和属性存储在变量中供以后使用.现在,如果我想在jQuery插件中具有相同的功能,我会从我的主代码中调用它,有点像这样:

$("#myId").ajaxIcon()
Run Code Online (Sandbox Code Playgroud)

按照惯例,我的插件需要返回传递给我的插件的原始jQuery对象,允许可链接性,但如果我这样做,我就失去了访问插件实例的方法和属性的能力.

现在,我知道你可以在我的插件中声明一个公共函数,有点像

$.fn.ajaxIcon = function(options) {
    return this.each(function () {
        //do some stuff
    }
}

$.fn.ajaxIcon.stop = function() {
    //stop stuff
}
Run Code Online (Sandbox Code Playgroud)

但是,在不违反返回原始jQuery对象的约定的情况下,我无法保留对我想要引用的插件的特定实例的引用.

我希望能够做到这样的事情:

var myIcon = $("myId").ajaxIcon(); //myIcon = a reference to the ajaxIcon 
myIcon.start();
//some stuff
myIcon.stop();
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

DEf*_*ion 91

如果您执行以下操作:

(function($){

$.fn.myPlugin = function(options) {
    // support multiple elements
    if (this.length > 1){
        this.each(function() { $(this).myPlugin(options) });
        return this;
    }

    // private variables
    var pOne = '';
    var pTwo = '';
    // ...

    // private methods
    var foo = function() {
        // do something ...
    }
    // ...

    // public methods        
    this.initialize = function() {
        // do something ...
        return this;
    };

    this.bar = function() {
        // do something ...
    };
    return this.initialize();
}
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

然后,您可以访问任何公共方法:

var myPlugin = $('#id').myPlugin();

myPlugin.bar();
Run Code Online (Sandbox Code Playgroud)

这是来自reallyevil.com 这篇非常有用的文章(2009年5月),它本身是来自learningjquery.com的本文(2007年10月)的扩展.