How to pass arguments to addEventListener listener function?

前端 未结 30 2107
谎友^
谎友^ 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));
    
    0 讨论(0)
  • 2020-11-22 00:36
        $form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
        function save(data, keyword, name, comment, event) {
    

    This is how I got event passed properly.

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

    Since your event listener is 'click', you can:

    someObj.setAttribute("onclick", "function(parameter)");
    
    0 讨论(0)
  • 2020-11-22 00:40

    I have very simplistic approach. This may work for others as it helped me. It is... When you are having multiple elements/variables assigned a same function and you want to pass the reference, the simplest solution is...

    function Name()
    {
    
    this.methodName = "Value"
    
    }
    

    That's it. It worked for me. So simple.

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

    Why not just get the arguments from the target attribute of the event?

    Example:

    const someInput = document.querySelector('button');
    someInput.addEventListener('click', myFunc, false);
    someInput.myParam = 'This is my parameter';
    function myFunc(evt)
    {
      window.alert(evt.currentTarget.myParam);
    }
    <button class="input">Show parameter</button>

    JavaScript is a prototype-oriented language, remember!

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

    The following approach worked well for me. Modified from here.

    function callback(theVar) {
      return function() {
        theVar();
      }
    }
    
    function some_other_function() {
      document.body.innerHTML += "made it.";
    }
    
    var someVar = some_other_function;
    document.getElementById('button').addEventListener('click', callback(someVar));
    <!DOCTYPE html>
    <html>
      <body>
        <button type="button" id="button">Click Me!</button>
      </body>
    </html>

    0 讨论(0)
提交回复
热议问题