javascript - adding multiple event listeners to one element -
so dilemma don't want write same code twice. once click event , touchstart
event.
here original code:
document.getelementbyid('first').addeventlistener('touchstart', function(event) { do_something(); }); document.getelementbyid('first').addeventlistener('click', function(event) { do_something(); });
how can compact this? there has simpler way!
maybe can use helper function this:
// events , args should of type array function addmultiplelisteners(element,events,handler,usecapture,args){ if (!(events instanceof array)){ throw 'addmultiplelisteners: '+ 'please supply array of eventstrings '+ '(like ["click","mouseover"])'; } //create wrapper able use additional arguments var handlerfn = function(e){ handler.apply(this, args && args instanceof array ? args : []); } (var i=0;i<events.length;i+=1){ element.addeventlistener(events[i],handlerfn,usecapture); } } function handler(e) { // things }; // usage addmultiplelisteners( document.getelementbyid('first'), ['touchstart','click'], handler, false);
Comments
Post a Comment