我坚持使用jQuery实现自定义事件处理,我试图从another thread采用。
我有两个彼此不认识的容器。但是它们中的每一个都应该能够处理可能由另一个容器中的某些用户操作触发的自定义事件。
我目前的实施是:
// In container 1
// register the custom event listener
$(div1).on('some-custom-event', function(e){
console.log('this: ', this)
});
// Add custom event trigger
$(this).on('click', function(e){
// do something
...
// Trigger the custom event.
$(this).trigger('some-other-custom-event'); // no console output
// Trigger the custom event with a new event object.
var e = jQuery.Event("some-other-custom-event"); // no console output
$(this).trigger(e);
});
// In container 2
// register the custom event listener
$(div2).on('some-other-custom-event', function(e){
console.log('this: ', this)
});
// Add custom event trigger
$(this).on('click', function(e){
// do something
...
// Trigger the custom event.
$(this).trigger('some-custom-event'); // no console output
// Trigger the custom event with a new event object.
var e = jQuery.Event("some-custom-event"); // no console output
$(this).trigger(e);
});
// Register the custom event listener for $(document)
$(document).on('some-custom-event', function(e){ // WORKS!
console.log('this: ', this)
});
但是,在将lister注册到我的容器时它不起作用。它仅在将侦听器绑定到$(document)
时或者只要在侦听它们的元素上触发事件时才起作用,这使得整个想法无用,因为我无法解耦这些元素。
我该如何正确实现这个?