Binding multiple events to a listener (without JQuery)?

johnkreitlow picture johnkreitlow · Jan 10, 2012 · Viewed 157.2k times · Source

While working with browser events, I've started incorporating Safari's touchEvents for mobile devices. I find that addEventListeners are stacking up with conditionals. This project can't use JQuery.

A standard event listener:

/* option 1 */
window.addEventListener('mousemove', this.mouseMoveHandler, false);
window.addEventListener('touchmove', this.mouseMoveHandler, false);

/* option 2, only enables the required event */
var isTouchEnabled = window.Touch || false;
window.addEventListener(isTouchEnabled ? 'touchmove' : 'mousemove', this.mouseMoveHandler, false);

JQuery's bind allows multiple events, like so:

$(window).bind('mousemove touchmove', function(e) {
    //do something;
});

Is there a way to combine the two event listeners as in the JQuery example? ex:

window.addEventListener('mousemove touchmove', this.mouseMoveHandler, false);

Any suggestions or tips are appreciated!

Answer

Isaac picture Isaac · Nov 20, 2014

Some compact syntax that achieves the desired result, POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });