I am trying to map a string to a function like so in Node.js.
function foo(data) {
//foo body
}
function bar(data) {
//bar body
}
var FUNCTION_MAP = {
"foo": foo,
"bar": bar
}
for (var event in FUNCTION_MAP) {
socket.on(event, function(data) {
FUNCTION_MAP[event](data);
});
}
Some hand-testing shows that event
will always be "bar"
, so the bar function is always called regardless of what event is invoked, i.e. whether the client calls socket.emit("foo", {})
or socket.emit("bar", {})
, the bar
function is always called on the server side. Even creating a new string object doesn't work.
for (var event in FUNCTION_MAP) {
socket.on(event, function(data) {
FUNCTION_MAP[new String(event)](data);
});
}
Why does event
retain the value "bar"
after the loop terminates? What can I do to create a string object that has its own value and doesn't reference the event
variable?