Ken Sherman Ken Sherman - 1 year ago 74
Javascript Question

How can I add an event listener for all events in javascript without listing them individually?

I'd like to accomplish the following code using a wildcard (that I don't think exists?)

myObject.element = document.getElementsByClassName('js-myObject');
myObject.element.addEventListener('mouseover', myObject.mouseover);

So far, I have the following

myObject.controller = function(e){
if( (e.type in myObject) && (typeof myObject[e.type] ==='function') ){

//but the listeners still have to be assigned as such
myObject.element = document.getElementsByClassName('js-myObject');
myObject.element.addEventListener('click', myObject.controller);
myObject.element.addEventListener('mouseover', myObject.controller);

// but I want to do (and it doesn't work)
myObject.element.addEventListener('*', myObject.controller);

Any suggestions on methods other than an array of events and a foreach statement?

Edit, my current solution

I've accepted an answer below (there's no wildcard available, and it's a bad idea to parse potentially hundreds of events)

For those looking for a similar function, I've settled on the following approach, at least for now.

for(var prop in myObject){
if (!myObject.hasOwnProperty(prop){continue;}
if (typeof myObject[prop] !== 'function'){continue;}
myObject.element.addEventListener(prop, myObject[prop]);

The upside is a handler for custom events that I don't have to go back and add listeners for. The downside is that I have to ensure this function is called after every myObject.someEvent() is defined. I call it in myObject.init(); which works for me just fine. Note that this solution wouldn't fit my previous specs, because it uses a for/each loop -- but it accomplishes what i really wanted to accomplish and a big thanks to @torazaburo for clearly defining the technical limitations and lack of wisdom in my initial plan.

Answer Source
// but I want to do (and it doesn't work)
myObject.element.addEventListener('*', myObject.controller);

There is no such feature, and I doubt if you want hundreds of events on an element being listened for anyway.

By the way, instead of your roll-your-own architecture for a generic event handler in the form of your myObject.controller, you should use the under-appreciated approach involving the EventListener interface and the handleEvent method it defines.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download