在javascript中,当我使用addEventListener时,我想调用外部方法并将其传递给事件arg:
var secondParam= "titi";
element.addEventListener("keydown", handleEventFunc(event, secondParam));
...
handleEventFunc: function (eventArg, secondParam) {
var key = event.keyCode;
var toto = secondParam;
//do things
}
如果我使用闭包,那将是等效的:
var secondParam= "titi";
element.addEventListener("keydown", function (event) {
var key = event.keyCode;
var toto = secondParam;
//do things
}
你知道怎么做吗?
答案 0 :(得分:1)
如果您只是引用函数而不是调用它,这会自动发生,因为任何参数都将由调用上下文传递,在本例中为事件处理程序
element.addEventListener("keydown", obj.handleEventFunc);
var obj = {
handleEventFunc: function (event) { // tada, now works
var key = event.keyCode; // keep the names the same
//do things
}
}