Reputation: 486
I'm trying to add event listeners with a rule object, like this
keyMap = [
{name: "Up", type: "keydown", code: 87, action: function(){alert("up")}},
{name: "Down", type: "keydown", code: 83, action: function(){alert("down")}},
{name: "Left", type: "keydown", code: 65, action: function(){alert("left")}},
{name: "Right", type: "keydown", code: 68, action: function(){alert("right")}}
]
for(var keyAct of keyMap){
if( typeof keyAct.action === "function" ){
document.addEventListener(keyAct.type, function(e){
if(e.keyCode === keyAct.code){
keyAct.action(e);
}
});
}
}
Then w/a/s/d press all alerted "right". I rewrote the for
part like this:
for(var keyAct of keyMap){
(function(keyAct){
if( typeof keyAct.action === "function" ){
document.addEventListener(keyAct.type, function(e){
if(e.keyCode === keyAct.code){
keyAct.action(e);
}
});
}
})(keyAct);
}
It works, but is this the only way to do so? Can I do it more elegantly? I mean, this looks weird.
Upvotes: 2
Views: 56
Reputation: 29285
Create another function to binding events, try this:
for(var i = 0, len = keyMap.length; i < len; ++i) {
if( typeof keyMap[i].action === "function" ) {
binder(keyMap[i]);
}
}
function binder(keyAct) {
document.addEventListener(keyAct.type, function(e) {
if(e.keyCode === keyAct.code) {
keyAct.action(e);
}
});
}
Upvotes: 1
Reputation: 1074555
I always separate out builder functions like that, to avoid recreating the builder function unnecessarily and for clarity:
for(var keyAct of keyMap){
if( typeof keyAct.action === "function" ){
document.addEventListener(keyAct.type, buildHandler(keyAct));
}
}
// Elsewhere
function buildHandler(keyAct){
return function(e) {
if(e.keyCode === keyAct.code){
keyAct.action(e);
}
};
}
Side note: for-in
loops aren't designed for looping through array entries, they're for looping through the enumerable properties of objects. Using them on arrays will tend to get you into trouble (if you ever add enumerable non-index properties to an array, directly or by extending Array.prototype
). Details: Myths and realities of for..in
Upvotes: 0