问题描述
给定例如某种类的实例具有状态(例如活动,非活动,...)。该实例还将点击事件附加到例如一个链接,但事件处理程序根据实例的状态而做不同的事情。伪代码:
IF实例状态IS'活动'AND链接点击THEN调用函数A
如果实例状态为无效,并且链接被点击THEN调用函数B
...
我想知道正确处理这种情况是什么好的做法:
- 哪些模式常用于实现?
- 您是否在事件处理程序中使用条件? / li>
- 还是在状态改变时绑定和解除绑定的处理程序?
- 我是否缺少一些明显的其他/更好的解决方案?
更新
阅读答案到目前为止,在处理程序中似乎有一个很强的使用条件的趋势。虽然我秘密地希望我可能错过了一个替代方案,但我已经预料到了这一点。
我喜欢@ J-P的方法,因为它保持了方法的配对并分开状态,这似乎比简单的开关
或 if / else
语句更可扩展和可维护。
然而,我会非常有兴趣听到这是否在其他地方有所不同,也许使用不同语言的例子?
我将保留相同的处理程序并调用相应的方法。
var Foo =(function(){
function Foo(){
this.state ='active';
}
Foo.methodMapping = {
active:'a',
inactive:'b'
};
Foo.prototype = {
a:function(){}
b:function(){},
处理函数:function(el){
//这将处理事件,我猜
//(假设`this`指的是实例,而不是元素)
var state = this。 state;
if(State in Foo.methodMapping){
return this [Foo.methodMapping [state]]。apply(this,arguments);
} else {
// (概率不需要覆盖这种情况)
}
}
};
retur n Foo;
}());
Given e.g. a class instance of some sort has a state (e.g. 'active', 'inactive', …). The instance also attaches a click event to e.g. a link but the event handler does something different depending on the instance's state.
Pseudo code:
IF instance state IS 'active' AND link is clicked THEN call function A
IF instance state IS 'inactive' AND link is clicked THEN call function B
…
I'm wondering what's considered good practice to handle this case properly:
- Which patterns are commonly in use to achieve this?
- Are you using a conditional in the event handler?
- Or are binding and unbinding handlers when the state changes?
- Am I missing some obvious other/better solution?
UPDATE
While reading the answers so far, there seems to be a strong tendency towards the usage of a conditional within the handler. While I had secretly hoped that I might have missed an alternative, I've sort of expected this.
I like @J-P's approach since it keeps the pairing of method and state separately, which seems more scaleable and maintainable than a simple switch
or if/else
statement.However, I'd be very interested to hear if this is solved differently elsewhere, maybe using an example from a different language?
I would keep the same handler and call the appropriate method within.
var Foo = (function(){
function Foo() {
this.state = 'active';
}
Foo.methodMapping = {
active: 'a',
inactive: 'b'
};
Foo.prototype = {
a: function(){}.
b: function(){},
handler: function(el) {
// This'll handle the event, I guess
// (Assuming `this` refers to instance, not element)
var state = this.state;
if (state in Foo.methodMapping) {
return this[Foo.methodMapping[state]].apply(this, arguments);
} else {
// (prob don't need to cover this case)
}
}
};
return Foo;
}());
这篇关于Javascript模式:条件事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!