This template is called "promises". It is implemented by jQuery and dojo, among others, and one approach is to look at their code and see how they implement it.
, , (), , , . MSDN promises
gitHub : Promises GIST
function Promise () {
this._thens = [];
}
Promise.prototype = {
then: function (onResolve, onReject) {
this._thens.push({ resolve: onResolve, reject: onReject });
},
resolve: function (val) { this._complete('resolve', val); },
reject: function (ex) { this._complete('reject', ex); },
_complete: function (which, arg) {
this.then = which === 'resolve' ?
function (resolve, reject) { resolve(arg); } :
function (resolve, reject) { reject(arg); };
this.resolve = this.reject =
function () { throw new Error('Promise already completed.'); };
var aThen, i = 0;
while (aThen = this._thens[i++]) { aThen[which] && aThen[which](arg); }
delete this._thens;
}
};
( , . , , )