In the node.js/socket.io 开发者_JAVA技巧code accompanying this article the following code is used to hook up events:
socket.on('message', function(message) {
var handler = messageFactory[message.messageType];
$chatMessages.append(handler(message));
});
What is the logic/effect of referencing messageFactory as an array (or at least using [] symbols)? Does it create different handles for different messageType?
Thanks!
What is the logic/effect of referencing messageFactory as an array (or at least using [] symbols)? Does it create different handles for different messageType?
messageFactory is an object with two methods chat
and system
.
I would assume message.messageType
is either "chat"
or "system"
So messageFactory[message.messageType]
simply gets one of the two methods.
Then handler(message)
calls that method.
This is becuase messageFactory.chat === messageFactory["chat"]
If you take a look at the server file ("Listing 5: The chatRoom module.") you will see methods returning
return {
messageType: 'system',
text: originalNick + ' changed nick to ' + newNick
};
So the server returns a message object with a messageType
property thats read on the client, it appears that messageType is only "chat"
or "system"
.
That code is basically the OO Command Design Pattern. It's running a different command based on the type of object returned
精彩评论