How to pass arguments to addEventListener listener function?

前端 未结 30 2257
谎友^
谎友^ 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

    Quite and old question but I had the same issue today. Cleanest solution I found is to use the concept of currying.

    The code for that:

    someObj.addEventListener('click', some_function(someVar));
    
    var some_function = function(someVar) {
        return function curried_func(e) {
            // do something here
        }
    }
    

    By naming the curried function it allows you to call Object.removeEventListener to unregister the eventListener at a later execution time.

提交回复
热议问题