How can i register "on" events in loop:
evetns = [
"click"
"mouseover"
...
]
for(events...) {
$(document).on(events[i], 'someTarget', function() {...});
}
How can i register "on" events in loop:
evetns = [
"click"
"mouseover"
...
]
for(events...) {
$(document).on(events[i], 'someTarget', function() {...});
}
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.
case 'click': return myClickFn(e); (and no break)? I'd pass the whole event object to the individual handlers in case they want to stop propagation or whatever.If i understand you correctly this should do what you want
var events = ['click', 'mouseover'];
console.log($('.dog'))
function registerEvents() {
events.forEach(function(value, index) {
$(".dog").on(value, onEvent); // Replace ".dog" with your own selctor
});
}
function onEvent(event) {
console.log(event.type);
}
registerEvents();
If you want to repeat registerEvents() every minute you could do something like
setInterval(registerEvents, 60000) // Repeat every minute