How to pass arguments to addEventListener listener function?

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

    You could pass somevar by value(not by reference) via a javascript feature known as closure:

    var someVar='origin';
    func = function(v){
        console.log(v);
    }
    document.addEventListener('click',function(someVar){
       return function(){func(someVar)}
    }(someVar));
    someVar='changed'
    

    Or you could write a common wrap function such as wrapEventCallback:

    function wrapEventCallback(callback){
        var args = Array.prototype.slice.call(arguments, 1);
        return function(e){
            callback.apply(this, args)
        }
    }
    var someVar='origin';
    func = function(v){
        console.log(v);
    }
    document.addEventListener('click',wrapEventCallback(func,someVar))
    someVar='changed'
    

    Here wrapEventCallback(func,var1,var2) is like:

    func.bind(null, var1,var2)
    

提交回复
热议问题