Lemec Cinq
Lemec Cinq

Reputation: 301

Javascript addEventListener : pass argument to external event handler

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?

Upvotes: 1

Views: 710

Answers (1)

adeneo
adeneo

Reputation: 318162

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
    }
}

Upvotes: 2

Related Questions