2013-04-24 95 views
0

我有我听一个自定义的事件中:监听事件的多个功能

$(document).on('MyCustomEvent', function(e, data) { 

}); 

我的问题是,我想知道什么时候MyCustomEvent有很多不同的功能内被解雇。我不想在每个函数中附加事件处理程序,因为它没有任何意义,并可能会覆盖彼此。

什么我之后是这样的:

function one(){ 

    //"when MyCustomEvent is fired, do stuff with the 'data' here" 
} 

function two(){ 

    //"when MyCustomEvent is fired, do stuff with the 'data' here" 
} 

回答

1

什么是与连接所有这些功能作为事件处理程序的问题?

$(document).on('MyCustomEvent', function(e, data) { 
    one(data); 
}); 

$(document).on('MyCustomEvent', function(e, data) { 
    two(data); 
}); 

你当然会需要更改签名,以便函数接受data作为参数。我已经分别附加了这两个函数,因为通常以这种模块化方式附加处理程序是唯一的方法。

你也可以使用一个命名空间的事件,这样就可以相互独立地分离的处理程序:

$(document).on('MyCustomEvent.one', function(e, data) { 
    one(data); 
}); 

$(document).on('MyCustomEvent.two', function(e, data) { 
    two(data); 
}); 

$(document).trigger('MyCustomEvent'); // both functions are called 
$(document).off('MyCustomEvent.one'); 
$(document).trigger('MyCustomEvent'); // only two() is called 
+0

我还以为你绑定事件侦听器第二次将覆盖第一个。但我想那不是那种情况 – Johan 2013-04-24 11:52:02