Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to prevent multiple calls of a custom event handler when using the Observer Pattern in jQuery
    primarykey
    data
    text
    <p>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.</p> <p>Here is some example code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-1.4.4.js"&gt;&lt;/script&gt; &lt;script&gt; $(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'); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="someDiv"&gt; &lt;span&gt;a span&lt;/span&gt; &lt;span&gt;another span&lt;/span&gt; &lt;/div&gt; &lt;div id="someOtherDivAddedBySomeOtherGuyLaterOn"&gt; &lt;span&gt;a span&lt;/span&gt; &lt;span&gt;another span&lt;/span&gt; &lt;/div&gt; &lt;p&gt;&lt;button type="button" id="clickMe"&gt;Click Me&lt;/button&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload