1

In Javascript, when I use addEventListener, I would like to call an external method and pass it an event arg:

var secondParam= "titi";
element.addEventListener("keydown", handleEventFunc(event, secondParam));
   ...
handleEventFunc: function (eventArg, secondParam) {
    var key = event.keyCode;
    var toto = secondParam;
    //do things
}

It would be working equivalent if I were using closure:

var secondParam= "titi";
element.addEventListener("keydown", function (event) {
        var key = event.keyCode;
        var toto = secondParam;
        //do things
}

Do you know how to do this?

1
  • It's not you who is supposed to call the function. It's the browser, when the event happens. Hence you have to give the browser a function to call. Commented Sep 20, 2017 at 16:21

1 Answer 1

2

This happens automagically if you just reference the function instead of calling it, as any arguments will be passed by the calling context, in this case the event handler

element.addEventListener("keydown", obj.handleEventFunc);

var obj = {
    handleEventFunc: function (event) { // tada, now works
        var key = event.keyCode; // keep the names the same
        //do things
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.