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

use*_*102 2 javascript jquery jquery-plugins

请考虑以下基本代码:

(function($) {
    $.fn.myPlugin = function(settings) {
        return this.each(function() {
            //whatever
        });
    };
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢.

Mat*_*att 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);
    };
});
Run Code Online (Sandbox Code Playgroud)

请注意,我们已经通过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
        };
    };
});
Run Code Online (Sandbox Code Playgroud)

然后;

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

alert(something.output('val')); // Lemon
Run Code Online (Sandbox Code Playgroud)

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