Javascript 侦听多个函数中的事件
我有一个自定义事件,我会收听:Javascript 侦听多个函数中的事件,javascript,jquery,Javascript,Jquery,我有一个自定义事件,我会收听: $(document).on('MyCustomEvent', function(e, data) { }); 我的问题是,我想知道很多不同的函数何时触发了MyCustomEvent。我不想在每个函数中附加事件处理程序,因为它没有任何意义,可能会相互覆盖 我想要的是这样的东西: function one(){ //"when MyCustomEvent is fired, do stuff with the 'data' here" } funct
$(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"
}
将所有这些函数作为事件处理程序附加有什么问题
$(document).on('MyCustomEvent', function(e, data) {
one(data);
});
$(document).on('MyCustomEvent', function(e, data) {
two(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
我认为第二次绑定事件侦听器时,它会覆盖第一次绑定。但我想情况并非如此