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

标签 javascript jquery jquery-plugins

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

;(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>同级container .

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

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

    }
});

现在当函数 onSomething从我的插件内部调用,我如何调用引用实例 onSomething 的插件公共(public)方法函数是从哪里调用的?

例如,第一个 container 发生了一些事情div 和 onSomething第一次调用函数 container分区。

为了让它更清楚一点,我尝试通过 this实例到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

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

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

关于javascript - jQuery 从回调函数内部调用插件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112514/

相关文章:

javascript - knockout : Why is there an empty object sent along?

jquery - 我怎样才能得到这个效果?

javascript - 如何将变量传递给queryselectorAll?

javascript简单对象创建测试: opera leaks?

jquery - 迭代使用 session 访问的列表

javascript - 如果存在另一个请求,如何停止ajax请求

php - Codeigniter JQuery Ajax

jquery复选框操作需要帮助

jquery - 使用 jQuery jPut 将 JSON 转换为 HTML

javascript - 路由/重定向不在 React Router 4 和 Redux 授权中呈现