我是原型机制,允许其他模块订阅我们框架的主要事件,并使用与事件(约定)一起传递的延迟数组来控制逻辑流。
如果以下示例中有4个订阅事件的事件处理程序,如果其中一个延迟被拒绝,则整个机制应终止执行。
目前为了防止事件处理程序(插入模块)执行我在每个处理程序的顶部检查是否
!$.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
if (hasRejected) return false;
一旦事件被解雇,即使我$.unbind('OnPreRender')
所有4名处理程序仍然会被解雇。在OnPreRender发生后,有没有办法防止这种情况发生?
var globalDeferred = $.Deferred(function(){setTimeout(function(){ console.log('%cglobal deferred','color : blue');}, 0)});
var deferredArray = [globalDeferred.promise()];
dataRoles.on('OnPreRender', function (e, options) {
var hasRejected = !$.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
if (hasRejected) return false;
var d = $.Deferred();
options.deferredArray.push(d.promise());
var rand = Math.floor(Math.random()*1000);
setTimeout(function(){
console.log("(1) in "+rand+" ms");
d.resolve();
},rand);
return $.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
});
dataRoles.on('OnPreRender', function (e, options) {
var hasRejected = !$.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
if (hasRejected) return false;
var d = $.Deferred();
options.deferredArray.push(d.promise());
var rand = Math.floor(Math.random()*1000);
setTimeout(function(){
console.log("(2) in "+rand+" ms");
d.reject();
},rand);
});
dataRoles.on('OnPreRender', function (e, options) {
var hasRejected = !$.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
if (hasRejected) return false;
var d = $.Deferred();
options.deferredArray.push(d.promise());
var rand = Math.floor(Math.random()*1000);
setTimeout(function(){
console.log("(3) in "+rand+" ms");
d.resolve();
},rand);
});
dataRoles.on('OnPreRender', function (e, options) {
var hasRejected = !$.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
if (hasRejected) return false;
var d = $.Deferred();
options.deferredArray.push(d.promise());
var rand = Math.floor(Math.random()*1000);
setTimeout(function(){
console.log("(4) in "+rand+" ms");
d.resolve();
},rand);
return $.grep(options.deferredArray,function(item){return item.state() == "rejected" }) == 0;
});
globalDeferred.reject();
$.when.apply($, deferredArray).then(function () {
console.log('%csuccess','color : green');
},function () {
console.log("%cfail","color : red");
});
dataRoles.trigger('OnPreRender', { deferredArray : deferredArray});
答案 0 :(得分:1)
这将解决您的问题。你可以用这个
替换你的解开/关闭e.stopImmediatePropagation();