【问题标题】:jQuery call plugin method from inside callback functionjQuery从回调函数内部调用插件方法
【发布时间】:2013-04-19 19:51:44
【问题描述】:

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

;(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

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

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

    }
});

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

例如,first container div 发生了一些事情,而 onSomething 函数仅被调用 first container div。

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

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

在我看来,这看起来很不对劲,所以一定有更好的方法......还是没有?

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    我不确定这是否是最好的主意,但您可以将当前对象作为参数传递。假设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 asobject` 让我们举一个具体的例子。

    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
    

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

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

    【讨论】:

    • 是的,我在这里做了和你一样的事情 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 2015-04-01
    相关资源
    最近更新 更多