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?
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?
Share Improve this question asked Apr 13, 2012 at 13:30 Daniel SloofDaniel Sloof 12.7k14 gold badges75 silver badges108 bronze badges1 Answer
Reset to default 10You can wrap it in another function:
initialize: function() {
// ...
var client = this;
this.socket.on('message', function(data) { client.on_message(data); });
In newer browsers (or Node.js) you can alternatively use a function on the Function
prototype called "bind":
this.socket.on('message', this.on_message.bind(this));
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 this
value.