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

Javascript jQuery从回调函数内部调用插件方法,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,我使用的是一个样板插件设计,看起来像这样 ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.prototype = { init: 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 );
现在假设我有两个
,它们具有相同的类
容器

现在我在这些div上调用我的
test
插件

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

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

例如,第一个
container
div发生了一些问题,并且只为第一个
container
div调用了
onSomething
函数

为了更清楚一点,我尝试将
这个
实例传递给
onSomething
函数,这样我就公开了所有的插件数据,然后我可以做如下操作

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

对我来说,这看起来很错误,所以一定有更好的方法。。。或者不是?

我不确定这是否是最好的主意,但您可以将当前对象作为参数传递。比如说
onSomething:function(obj){}
因此,每当插件调用“onSomething”时,您可以这样调用它:“onSomething(this)”,然后将对象称为
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
希望这有帮助,如果不够清楚,请告诉我


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

是的,我和你在这里做的一样:)