Reputation:
this might have been asked, but doing a brief search, I couldn't find an answer.
I am creating a function to handling user events, and I don't know how to pass a parameter into the function, without ruining the event handler.
Here is my code:
function keydown(e) {
e = e || window.event;
if (e.keyCode == '38' || e.keycode == '40' || e.keyCode == '37' || e.keyCode == '39')
e.preventDefault();
switch(e.keyCode){
case 38: //Up
console.log('UP');
break;
case 40: //Down
console.log('DOWN');
break;
case 37: // Left
console.log('LEFT');
break;
case 39: //Right
console.log('RIGHT');
break;
}}
I would like something like this:
function keydown(e, myParam) {
console.log(myParam); // Console logging the second parameter
e = e || window.event;
if (e.keyCode == '38' || e.keycode == '40' || e.keyCode == '37' || e.keyCode == '39')
e.preventDefault();
switch(e.keyCode){
case 38: //Up
console.log('UP');
break;
case 40: //Down
console.log('DOWN');
break;
case 37: // Left
console.log('LEFT');
break;
case 39: //Right
console.log('RIGHT');
break;
}
}
Anybody got any suggestions?
Upvotes: 0
Views: 1046
Reputation: 94101
You can use a closure:
function keydown(param) {
return function(e) {
console.log(param)
...
}
}
elem.addEventListener('keydown', keydown(param))
Upvotes: 2