开发一个返回给定对象的jQuery插件,而不是jQuery对象本身!

时间:2010-04-01 17:31:21

标签: javascript jquery jquery-plugins

考虑以下基本代码:

(function($) {
    $.fn.myPlugin = function(settings) {
        return this.each(function() {
            //whatever
        });
    };
});

该插件返回一个jQuery对象。问题是我应该如何编写一个返回自定义对象的插件,以便我可以这样做:

var api = $('div.myelement').myPlugin();
api.onMyEventName(function(e, whateverParam) {
    //whatever
});

如果您能编写一些描述我如何操作的代码,如何在自定义api对象上调用onMyEventName函数,我们将非常感激...

感谢。

2 个答案:

答案 0 :(得分:14)

(function($) {
    function MyApi($this, settings) {
        this.$this = $this;
        this.settings = settings;
    };

    MyApi.prototype.output = function (val) {
       // use this.$this to access the original jQuery object

       return this.settings[val];
    };

    $.fn.myPlugin = function(settings) {
        return new MyApi(this, settings);
    };
});

注意我们已将this$.fn.myPlugin()传递到MyApi构造函数;这允许您访问myPlugin()方法中最初调用MyApi的jQuery对象。

您也可以使用对象文字语法执行相同的操作:

(function($) {
    $.fn.myPlugin = function(settings) {
        return {
            settings: settings,
            output: function (val) {
                // use this.$this to access the original jQuery object

                return this.settings[val];
            },
            $this: this
        };
    };
});

然后;

var something = $('#something').myPlugin({
   val: 'Lemon'
});

alert(something.output('val')); // Lemon

...再次,我们已将this(jQuery对象)的值捕获到新构造的对象上的属性$this中,以获取对原始jQuery对象的访问权。

答案 1 :(得分:0)

有一个great article by Hector Virgen详细说明了一个可能的解决方案(也用于引导程序)来解决这个问题。

关键时刻基本上是将您的API对象存储在节点的数据部分中:

$.fn.myplugin = function() {
    return $.each(function() {
        ...
        myplugin = new MyPlugin(this)
        ...
        $(this).data('myplugin', myplugin);
    }
}

此后,用户可以通过以下方式轻松访问该对象:

$(this).data("myplugin")

此解决方案的一个可能有用的扩展可能是定义mypluginapi方法作为速记,用于访问您的API对象:

$.fn.mypluginapi = function() {
    return $(this).myplugin().data('myplugin')
}