Royi Namir
Royi Namir

Reputation: 148524

Using jQuery.Deferred over variable?

When ajax complete I can use done,error,always deferred methods . But I can do this because jqXHR object, is derived from a Deferred object.

But How can I mimic this behavior over this simple example :

I have a variable named t.

I want the done function to be called when t get's its value.

Something like this : (psuedo)

var t;
setTimeout(function (){t=100;},3000);
t.done(function (){alert('');}); //im expecting this alert after 3 seconds.

How can I do this ?

p.s. I know i can call the alert in the callback function(obviously). but again. I want to apply the deferred behaviour

Upvotes: 1

Views: 1132

Answers (1)

Bergi
Bergi

Reputation: 664307

You can't use just a variable which you assign to. Instead, create a jQuery.Deferred object manually, and .resolve() it:

var t = new $.Deferred();
setTimeout(function() {
    t.resolve(100);
}, 3000);
t.done(function(val) {
    alert(val);
}); // this will alert "100" after 3 seconds

Upvotes: 1

Related Questions