我想您想将其用于异步任务。这是一个有点类似的解决方案:
var o = {
parma1: 'a',
param2: 'b',
doAsyncStuff: function(complete, error){
var someData = 0;
setTimeout(function(){
someData = 1;
complete(someData);
}, 500);
//or if something went wrong:
//error(someErrorData);
}
}
o.doAsyncStuff(function(data){
console.log('complete', data);
}, function(data){
console.log('error', data);
});
http://jsfiddle.net/pA99q/1/
根据要求,使用延迟对象的更新版本。progress
如果您可能需要,我也可以自由地包括在内:
var task = (function($){
var dfd = $.Deferred(),
cls = function(){
console.log('param passed:', arguments);
for(var i = 0; i < 5; i++){
var count = 0;
setTimeout(function(){
count++;
dfd.notify({ msg: 'interation ' + count + ' complete' });
if(count === 5)
dfd.resolve({ something: 1 });
//if anything goes wrong,
//you can always reject the deferred:
//dfd.reject(args);
}, 1000 * i);
}
};
cls.prototype = {
done: dfd.promise().done,
fail: dfd.promise().fail,
always: dfd.promise().always,
progress: dfd.promise().progress
};
return cls;
})(jQuery);
var t = new task({ foo: 'bar' }, 123, 'baz');
t.progress(function(data){
console.log('progress:', data);
}).done(function(){
console.log('done');
}).fail(function(){
console.log('fail');
}).always(function(){
console.log('always');
});
http://jsfiddle.net/hGFbt/