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

jQuery call plugin method from inside callback function

本文关键字:内部 回调 函数 方法 调用 插件 jQuery      更新时间:2023-09-26

我正在使用一个样板插件设计,看起来像这样,

;(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函数被调用?

例如,first containerdiv和onSomething函数只对first containerdiv调用。

为了更清楚一点,我试图将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

希望有帮助,如果不够清楚请告诉我。

哦,等等,这就是你做的。