JavaScript: Keeping track of eventListeners on DOM elements

Posted by bobthabuilda on Stack Overflow See other posts from Stack Overflow or by bobthabuilda
Published on 2010-04-27T05:04:24Z Indexed on 2010/04/27 5:43 UTC
Read the original article Hit count: 427

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery