2013年2月12日 星期二

[JS] deferred.promise()的應用

今天在看jQuery的.animation()程式碼的時候注意到的。

之前就有稍微研究一下jQuery的deferred物件,今天看到他被用在animation的程式碼裡面,而且是我之前沒學過的用法,於是在這邊筆記一下。
var obj = { speak: function(name){alert(name);} }
    deferred = $.Deferred();
deferred.promise(obj);
obj.done(function(name){obj.speak(name)});
deferred.resolve("Kevin");

After being promised, the object would would be extended with some of the deferred object's function like "done", "fail", "always".

As the above, though the promised object can't resolve it self, but the deferred object who promise it can. And it can even pass an argument on resolving or rejecting it.

The deferred object really helps dealing with asyncronise problems in javascript.