JavaScript只有在某些条件为真时才允许执行各种函数

我有一个附加到各种元素的事件处理程序列表,但我想在某个条件为真时禁用其中一些 。 这种情况(即布尔值)会动态变化,并且在变化时无法预测。 这是我目前所做的。

function foo () { if (someCondition) { return; } // foo does something } function bar () { if (someCondition) { return; } // bar does something } ...etc 

这没关系,但在每个函数中使用if块实际上是多余的。 有没有更简洁的方法来管理这个? 我想知道我是否可以将两个事件处理程序附加到一个元素,并且只有在另一个元素返回true时才执行一个。

您可以编写一个函数,将函数转换为仅在条件为真时运行的函数:

 function conditionalize( fn ) { return function() { if (someCondition) return; return fn.apply(this, arguments); }; } 

然后:

 var foo = conditionalize(function() { // stuff that foo does }); 

你可以使用像jQuery事件处理方法的委托方法,试试这个:

 var callbacks = [foo, bar]; function delegate() { // this is the only event handler var i, len; for(i=0, len = callbacks.length; i < len; i++) { if(callbacks[i].apply(this, arguments)){ continue; // return value of this callback is true then continue } else { break; // ignore other callbacks } } } function foo () { // foo does something } function bar () { // bar does something }