[英]Defining Handler Functions in a Prototye
I am trying to create a JavaScript prototype that will allow me to handle the outcome of a process in a similar way to the jQuery ajax call works. 我正在尝试创建一个JavaScript原型,该原型将允许我以类似于jQuery ajax调用工作的方式处理流程的结果。 For example:
例如:
var request = $.ajax({
//params here
})
.done(function(data, textStatus, jqXHR) {
//action here
})
.fail(function (jqXHR, textStatus, errorThrown) {
//action here
});
How do I declare my prototype to have the done
and fail
events (if that is even the correct term to use) and make sure that they are fired under a condition from within the prototype logic? 如何声明原型具有
done
和fail
事件(即使这是使用的正确术语),并确保它们在原型逻辑内的条件下被触发?
My desired call would be something like this: 我想要的电话将是这样的:
var o = myObj({
parma1: 'a',
param2: 'b'
})
.done(function() {
//action here
});
.fail(function() {
//action here
});
I hope this makes sense as I do not know what the correct terminologies are for this process :( 我希望这是有道理的,因为我不知道此过程的正确术语是什么:(
I am using jQuery so if there is a better solution using jQuery then that is fine. 我正在使用jQuery,因此,如果有使用jQuery的更好的解决方案,那就很好。
I suppose you want to use this for an asyncrhonous task. 我想您想将此用于异步任务。 Here is a somewhat similar solution:
这是一个有点类似的解决方案:
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/ http://jsfiddle.net/pA99q/1/
As requested, an updated version using deferred objects. 根据要求,使用延迟对象的更新版本。 I took myself the freedom to include
progress
as well, in case you might need it: 如果您可能需要
progress
,我也让自己自由地包括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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.