How to pass arguments to addEventListener listener function?

前端 未结 30 2270
谎友^
谎友^ 2020-11-21 23:56

The situation is somewhat like-

var someVar = some_other_function();
someObj.addEventListener(\"click\", function(){
    some_function(someVar);
}, false);
<         


        
30条回答
  •  盖世英雄少女心
    2020-11-22 00:35

    If I'm not mistaken using calling the function with bind actually creates a new function that is returned by the bind method. This will cause you problems later or if you would like to remove the event listener, as it's basically like an anonymous function:

    // Possible:
    function myCallback() { /* code here */ }
    someObject.addEventListener('event', myCallback);
    someObject.removeEventListener('event', myCallback);
    
    // Not Possible:
    function myCallback() { /* code here */ }
    someObject.addEventListener('event', function() { myCallback });
    someObject.removeEventListener('event', /* can't remove anonymous function */);
    

    So take that in mind.

    If you are using ES6 you could do the same as suggested but a bit cleaner:

    someObject.addEventListener('event', () => myCallback(params));
    

提交回复
热议问题