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

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

本文介绍了JavaScript只有在某些条件为真时才允许执行各种函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of event handlers that are attached to various elements, but I want to disable some of them when a certain condition is true. This condition (i.e. boolean value) changes dynamically and it is not predictable when it changes. Here is what I do currently.

function foo () {
    if (someCondition) {
        return;
    }

    // foo does something
}

function bar () {
    if (someCondition) {
        return;
    }

    // bar does something
}

...etc

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

This is alright, but it's really redundant to have the if block in each function. Is there a more concise way to manage this? I was wondering if I can attach two event handlers to one element, and only execute one if the other returned true.

推荐答案

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

You could write a function that turns a function into one that only runs if the condition is true:

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

然后:

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

这篇关于JavaScript只有在某些条件为真时才允许执行各种函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 21:47