繁体   English   中英

回调函数内部的jQuery调用插件方法

[英]jQuery call plugin method from inside callback function

我使用的样板插件设计如下所示,

;(function ( $, window, document, undefined ) {

    var pluginName = "test",
        defaults = {};

    function test( element, options ) {
        this.init();
    }

    test.prototype = {   
        init: function() {}
    }

    $.fn.test = function(opt) {
        // slice arguments to leave only arguments after function name
        var args = Array.prototype.slice.call(arguments, 1);
        return this.each(function() {
            var item = $(this), instance = item.data('test');
            if(!instance) {
                // create plugin instance and save it in data
                item.data('test', new test(this, opt));
            } else {
                // if instance already created call method
                if(typeof opt === 'string') {
                    instance[opt].apply(instance, args);
                }
            }
        });
    };

})( jQuery, window, document );

现在说我有两个具有相同类container <div>

现在我会像这样在这些div上调用我的test插件,

$(".container").test({
    onSomething: function(){

    }
});

现在,当从插件内部调用函数onSomething时,如何调用引用实例onSomething函数的插件公共方法呢?

例如,第一个 container div发生了某些情况,仅第一个 container div调用了onSomething函数。

为了更清楚一点,我尝试this实例传递给onSomething函数,这样,我公开了所有插件数据,然后可以执行类似的操作,

onSomething(instance){
   instance.someMethod();
   instance.init();
   //or anything i want
}

对我来说,这看起来很不对劲,所以必须有更好的方法...

我不确定这是否是最好的主意,但是您可以将当前对象作为参数传递。 假设onSomething : function(obj) { } So whenever "onSomething" is called by the plugin, you can call it like this: "onSomething(this)" and then refer to the object as object。让我们举一个具体的例子。

var plugin = function (opts) {
 this.onSomething = opts.onSomething;
 this.staticProperty = 'HELLO WORLD';
 this.init = function() {
  //Whatever and lets pretend you want your callback right here.
  this.onSomething(this);
 }
}
var test = new Plugin({onSomething: function(object) { alert(object.staticProperty) });
test.init(); // Alerts HELLO WORLD

希望这会有所帮助,请告诉我它是否还不够清楚。

哦,等等,这就是您所做的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM