How to pass arguments to addEventListener listener function?

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

    Sending arguments to an eventListener's callback function requires creating an isolated function and passing arguments to that isolated function.

    Here's a nice little helper function you can use. Based on "hello world's" example above.)

    One thing that is also needed is to maintain a reference to the function so we can remove the listener cleanly.

    // Lambda closure chaos.
    //
    // Send an anonymous function to the listener, but execute it immediately.
    // This will cause the arguments are captured, which is useful when running 
    // within loops.
    //
    // The anonymous function returns a closure, that will be executed when 
    // the event triggers. And since the arguments were captured, any vars 
    // that were sent in will be unique to the function.
    
    function addListenerWithArgs(elem, evt, func, vars){
        var f = function(ff, vv){
                return (function (){
                    ff(vv);
                });
        }(func, vars);
    
        elem.addEventListener(evt, f);
    
        return f;
    }
    
    // Usage:
    
    function doSomething(withThis){
        console.log("withThis", withThis);
    }
    
    // Capture the function so we can remove it later.
    var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
    
    // To remove the listener, use the normal routine:
    someElem.removeEventListener("click", storeFunc);
    

提交回复
热议问题