簡體   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