Adding and Removing Event Listeners with parameters

后端 未结 4 414
我在风中等你
我在风中等你 2020-12-09 18:31

I am writing a vanilla JavaScript tool, that when enabled adds event listeners to each of the elements passed into it.

I would like to do something

4条回答
  •  遥遥无期
    2020-12-09 18:56

    This is invalid:

    arr[i].el.addEventListener('click', do_something(arr[i]));
    

    The listener must be a function reference. You cannot specify parameters at the time of listener assignment. A handler function will always be called with the event being passed as the first argument. To pass other arguments, you can wrap your listener into an anonymous function like so:

    elem.addEventListener('click', function(event) {
      do_something( ... )
    }
    

    To be able to remove via removeEventListener you just name the handler function:

    function myListener(event) {
      do_something( ... );
    }
    
    elem.addEventListener('click', myListener);
    

    To have access other variables in the handler function, you can use closures. E.g.:

    function someFunc() {
      var a = 1,
          b = 2;
    
      function myListener(event) {
        do_something(a, b);
      }
    
      elem.addEventListener('click', myListener);
    }
    

提交回复
热议问题