解决这个问题的一种方法是使用简单的保护抽象。它是这样工作的:
var sayHi = guard("enabled", function(){
alert("hi");
});
guard.deactivate("enabled");
sayHi(); // nothing happens
guard.activate("enabled");
sayHi(); // shows the alert
将其用于事件处理程序是类似的:
handleChange: guard("something", function(e){
// if 'something' is deactivated, the input won't change
this.setState({value: e.target.value});
})
// or
return <div onClick={guard("something", this.handleClick)}>click me!</div>
这是一个守卫的实现
var guard = function(key, fn){
return function(){
if (guard.flags[key]) {
return fn.apply(this, arguments);
}
};
};
guard.flags = {};
guard.activate = function(key){ guard.flags[key] = true };
guard.deactivate = function(key){ guard.flags[key] = false };