JavaScript: Keeping track of eventListeners on DOM elements
- by bobthabuilda
What is the best way to keep track of eventListener functions on DOM elements? Should I add a property to the element which references the function like this:
var elem = document.getElementsByTagName( 'p' )[0];
function clickFn(){};
elem.listeners = { click: [clickFn, function(){}] };
elem.addEventListener( 'click', function(e){ clickFn(e); }, false );
Or should I store it in my own variable in my code like below:
var elem = document.getElementsByTagName( 'p' )[0];
function clickFn(){};
// Using window for the sake of brevity, otherwise I wouldn't =D
// DOM elements and their listeners are referenced here in a paired array
window.listeners = [elem, { click: [clickFn, function(){}] }];
elem.addEventListener( 'click', function(e){ clickFn(e); }, false );
Obviously the second method would be less obtrusive, but it seems it could get intensive iterating through all those possibilities.
Which is the best way and why? Is there a better way?