bsbak bsbak - 26 days ago 11
jQuery Question

jQuery register events in loop

How can i register "on" events in loop:

evetns = [
"click"
"mouseover"
...
]
for(events...) {
$(document).on(events[i], 'someTarget', function() {...});
}

Answer Source

Don't register events in a for loop is my answer.

The on() function delegates the events on the same object, so there is no need for this kind of trickery. What you can do is to use events.join(' ').

This way the $(document) object gets all the events in a string separated by a single space resulting in:

$(document).on('click mouseover ...', function(){/**/});

Now the trick to optimize this, I'd say is use an eventHandler that maps specific functions to separate events.

$(document).on(events.join(' '), myEventHandler);

function myEventHandler(e){
    switch (e.type){
        case 'click': return myClickFn(e);
        case 'mouseover': return myOverFn(e);
        default: return false;
    }
}

This way all functionality can be kept separate in the browser's memory.

Imagine without the switch statement, you can achieve all events to fire the same function at the same time the event occurred. If that is what you need however, I suggest to use throttle or debounce to handle this use-case.