How to pass arguments to addEventListener listener function?

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

    Function.prototype.bind() is the way to bind a target function to a particular scope and optionally define the this object within the target function.

    someObj.addEventListener("click", some_function.bind(this), false);
    

    Or to capture some of the lexical scope, for example in a loop:

    someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
    

    Finally, if the this parameter is not needed within the target function:

    someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
    
    0 讨论(0)
  • 2020-11-22 00:56

    This question is old but I thought I'd offer an alternative using ES5's .bind() - for posterity. :)

    function some_func(otherFunc, ev) {
        // magic happens
    }
    someObj.addEventListener("click", some_func.bind(null, some_other_func), false);
    

    Just be aware that you need to set up your listener function with the first param as the argument you're passing into bind (your other function) and the second param is now the event (instead of the first, as it would have been).

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 00:56

    Other alternative, perhaps not as elegant as the use of bind, but it is valid for events in a loop

    for (var key in catalog){
        document.getElementById(key).my_id = key
        document.getElementById(key).addEventListener('click', function(e) {
            editorContent.loadCatalogEntry(e.srcElement.my_id)
        }, false);
    }
    

    It has been tested for google chrome extensions and maybe e.srcElement must be replaced by e.source in other browsers

    I found this solution using the comment posted by Imatoria but I cannot mark it as useful because I do not have enough reputation :D

    0 讨论(0)
  • 2020-11-22 00:57

    Also try these (IE8 + Chrome. I dont know for FF):

    function addEvent(obj, type, fn) {
        eval('obj.on'+type+'=fn');
    }
    
    function removeEvent(obj, type) {
        eval('obj.on'+type+'=null');
    }
    
    // Use :
    
    function someFunction (someArg) {alert(someArg);}
    
    var object=document.getElementById('somObject_id') ;
    var someArg="Hi there !";
    var func=function(){someFunction (someArg)};
    
    // mouseover is inactive
    addEvent (object, 'mouseover', func);
    // mouseover is now active
    addEvent (object, 'mouseover');
    // mouseover is inactive
    

    Hope there is no typos :-)

    0 讨论(0)
  • 2020-11-22 00:57

    I was stuck in this as I was using it in a loop for finding elements and adding listner to it. If you're using it in a loop, then this will work perfectly

    for (var i = 0; i < states_array.length; i++) {
         var link = document.getElementById('apply_'+states_array[i].state_id);
         link.my_id = i;
         link.addEventListener('click', function(e) {   
            alert(e.target.my_id);        
            some_function(states_array[e.target.my_id].css_url);
         });
    }
    
    0 讨论(0)
提交回复
热议问题