adding multiple event listeners to one element

后端 未结 14 1400
夕颜
夕颜 2020-11-27 13:12

So my dilemma is that I don\'t want to write the same code twice. Once for the click event and another for the touchstart event.

Here is the original co

相关标签:
14条回答
  • 2020-11-27 13:42

    I just made this function (intentionally minified):

    ((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, events, handler)
    

    Usage:

    ((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, ['click', 'touchstart'], (event) => {
        // function body
    });
    

    The difference compared to other approaches is that the handling function is defined only once and then passed to every addEventListener.

    EDIT:

    Adding a non-minified version to make it more comprehensible. The minified version was meant just to be copy-pasted and used.

    ((element, event_names, handler) => {
    
        event_names.forEach( (event_name) => {
            element.addEventListener(event_name, handler)
        })
    
    })(element, ['click', 'touchstart'], (event) => {
    
        // function body
    
    });
    
    0 讨论(0)
  • 2020-11-27 13:47

    I have a small solution that attaches to the prototype

      EventTarget.prototype.addEventListeners = function(type, listener, options,extra) {
      let arr = type;
      if(typeof type == 'string'){
        let sp = type.split(/[\s,;]+/);
        arr = sp;   
      }
      for(let a of arr){
        this.addEventListener(a,listener,options,extra);
      }
    };
    

    Allows you to give it a string or Array. The string can be separated with a space(' '), a comma(',') OR a Semicolon(';')

    0 讨论(0)
提交回复
热议问题