2012-09-21 32 views
0

我有一個模塊,有一個內部循環(使用'settimeout')。每次定時器發生時,我都想發起回調。我試圖使用jQuery的Deferred對象,沒有運氣..喜歡的東西:使用jQuery的推遲與settimeout

$(function(){ 
    var module = new MyModule(); 
    $.when(module.init()).then("DO Something"); 
}); 

function MyModule(){ 

    this.d = $.Deferred(); 

} 

test.prototype.init = function(){ 
    clearTimeout(this.next); 

    var self = this; 

    /* Do Something */ 

    self.d.resolve(); 

    this.next = setTimeout(function(){ 
     self.init(); /* The problem is here - internal call to self */ 
    }, 4000); 
    return self.d.promise(); 
}; 

的問題是,計時器調用該方法內部,所以我不會有呼叫「於是(做某事);」的主要計劃。我可以使用舊的學校函數回調(傳遞迴調函數到模塊),但我真的想嘗試這些偉大的功能。

感謝,

的Yaniv

回答

2

一個延期真的不是你要找的內容,因爲這是一個一次性的交易 - 你可能想要的是一個回調列表。

jQuery提供了$ .Callbacks()這可能是你正在尋找的。

function MyModule(){ 

    this._initCallbacks = $.Callbacks(); 

} 

MyModule.prototype.onInit = function(cb) { 
    if (typeof cb === "function") { 
     this._initCallbacks.add(cb); 
    } 
}; 

MyModule.prototype.init = function(){ 
    clearTimeout(this.next); 

    var self = this; 

    this._callbacks.fire(); 

    this.next = setTimeout(function(){ 
     self.init(); 
    }, 4000); 

    return this; 
}; 

$(function(){ 
    var module = new MyModule(); 

    module.onInit(function() { 
     console.log("Do something"); 
    }); 

    module.init(); 
}); 

的jsfiddle:http://jsfiddle.net/SUsyj/

+0

好知道這一個。在我的情況下,我只需要一個回調就可以撥打所有的電話,這是不是有點矯枉過正? –

+0

如果你只保證有一個回調,那麼它可能是。這取決於您的要求,以及您是否認爲將來可能需要多次回調。 – dherman