在 jQuery 中使用观察者模式时如何防止自定义事件处理程序的多次调用
我正在使用 jQuery 来实现观察者模式。我在 $('body *') 上触发自定义事件,因为不知道哪些元素将响应该事件。也就是说,我希望我的开发人员同事能够添加代码来响应该事件,而我不必知道它。我遇到的问题是绑定到自定义事件的元素的任何子元素都会执行处理程序。有没有办法确保这些子元素不执行处理程序?请记住,我无法触发元素本身,因为该元素是未知的。如果可能的话,我想避免让目标元素添加类。
这是一些示例代码:
<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$(function() {
$('#clickMe').click(function() {
$('body *').trigger('myCustomEvent');
});
$('#someDiv').bind('myCustomEvent', function(e) {
alert('someDiv responding to myCustomEvent');
});
$('#someOtherDivAddedBySomeOtherGuyLaterOn').bind('myCustomEvent', function() {
alert('someOtherDivAddedBySomeOtherGuyLaterOn responding to myCustomEvent');
});
});
</script>
</head>
<body>
<div id="someDiv">
<span>a span</span>
<span>another span</span>
</div>
<div id="someOtherDivAddedBySomeOtherGuyLaterOn">
<span>a span</span>
<span>another span</span>
</div>
<p><button type="button" id="clickMe">Click Me</button></p>
</body>
</html>
I am using jQuery to implement the observer pattern. I am triggering a custom event on $('body *') because it is not know what elements will respond to the event. That is, I want to enable my fellow developers to add code to respond to the event without me having to know about it. The problem I am encountering is that any child elements of an element bound to the custom event execute the handler. Is there a way to make sure that these child elements do not execute the handler? Keep in mind that I can't trigger on the element itself, because that element is unknown. I would like to avoid having the target elements add a class if possible.
Here is some example code:
<html>
<head>
<title>test</title>
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$(function() {
$('#clickMe').click(function() {
$('body *').trigger('myCustomEvent');
});
$('#someDiv').bind('myCustomEvent', function(e) {
alert('someDiv responding to myCustomEvent');
});
$('#someOtherDivAddedBySomeOtherGuyLaterOn').bind('myCustomEvent', function() {
alert('someOtherDivAddedBySomeOtherGuyLaterOn responding to myCustomEvent');
});
});
</script>
</head>
<body>
<div id="someDiv">
<span>a span</span>
<span>another span</span>
</div>
<div id="someOtherDivAddedBySomeOtherGuyLaterOn">
<span>a span</span>
<span>another span</span>
</div>
<p><button type="button" id="clickMe">Click Me</button></p>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道是否有一种自动方法来防止子元素上的事件冒泡,但您可以手动停止已知子元素上的事件冒泡。例如:
更新:这是工作代码示例。
I don't know if there is an automatic way to prevent event bubbling on child elements, but you can manually stop bubbling on known child elements. For example:
UPDATE: Here is working code example.