Reputation: 6713
I have a module that has an internal loop (using 'settimeout'). I want to fire a callback each time the timer happens. I tried using jQuery's deferred object with no luck.. Something like:
$(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();
};
The problem is that the timer calls the method internally, so I will not have a call to ".then(Do Something);" of the main program. I can use the old school function callback (pass a callback function to the module) but I really wanted to try these great feature.
Thanks,
Yaniv
Upvotes: 0
Views: 1004
Reputation: 2892
A deferred really isn't what you're looking for because that's a one time deal - what you likely want is a Callback list.
jQuery provides that as $.Callbacks() which might be what you're looking for.
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/
Upvotes: 2