Note that there are some explanatory texts on larger screens.

plurals
  1. POSending data with an event listener
    primarykey
    data
    text
    <p>I have a predicament: I want to send some data with an event listener but also be able to remove the listener. Here's the standard closure approach...</p> <pre><code>var fn = function(e){method(e,data)}; el.addEventListener('click',fn,false); el.removeEventListener('click',fn,false); </code></pre> <p>and you could remove the event, just fine. But say, the element was removed from the DOM? Then, you'd be left with the <code>fn</code> function sitting around. After removing a couple thousand DOM elements, it will result in something of a memory leak.</p> <p>I've considered attaching a DOMNodeRemoved event handler, that would remove any left over functions/data along with the removed node. But apparently, that event isn't cross-browser compatible.</p> <p>The only other option I've come up with would be modifying the element's DOM. Consider...</p> <pre><code>el.MyEventData = function(e){method(e,data)}; el.addEventListener('click',el.MyEventData,false); el.removeEventListener('click',el.MyEventData,false); </code></pre> <p>Is modifying the DOM acceptable in this situation? The only sticky part of that solution is when you try to add more than one event listener. Let's say we made a custom function to parse the adding/removing of events...</p> <pre><code>function makeEvent(fn,data){ var dataFn = function(e){fn(e,data)}; //create object to hold all added events el.myEvents = {}; //make ID for this specific event var eventID = ranString(); //add the event to the events object el.myEvents[eventID] = [fn,dataFn]; //finally add the listener el.addEventListener('click',dataFn,false); } function destroyEvent(fn){ //find all fn references for(var id in el.myEvents){ if (el.myEvents[id][0] == fn){ el.removeEventListener('click',el.myEvents[id][1],false); el.myEvents[id] = null; } } } </code></pre> <p>It still modifies the DOM, as before, and certainly isn't a very elegant solution either. Does anyone know of any alternative, better method for passing data?</p> <p><em>EDIT</em>: So, I've looked into a little of jQuery's data/event scripts. I don't completely understand the code, so if someone would clarify, it would be helpful. But it seems as though they use a similar method, by making some type of el.cache property, that holds event data.</p>
    singulars
    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.
 

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