Original 'this' context with Socket.IO
javascript, prototype, socket.io
Solution
You 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.
Problem
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?