I have wrapped (client-side) socket.io in a prototype class:
Chat.Client = Class.create();
Chat.Client.prototype = {
initialize: function() {
...
this.socket.on('message', this.on_message);
...
},
on_message: function(data) {
this.add_chat_message(data.something);
}
do_something: function(something) {
...
}
This does not work because ‘this’ in on_message will be ‘SocketNamespace’. Traditionally I would work around this by just passing ‘this’ into the callback as an additional parameter, but because I am using socket.io, I cannot simply do this.
How can I solve this?
You can wrap it in another function:
In newer browsers (or Node.js) you can alternatively use a function on the
Functionprototype called “bind”:The “bind” function returns a function that, when called, will force the original function (“on_message”) to be invoked with the given value as the
thisvalue.