adding multiple event listeners to one element

后端 未结 14 1444
夕颜
夕颜 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
    
    });
    

提交回复
热议问题