Original 'this' context with Socket.IO

I wrapped the (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 the 'this' in on_message will be "SocketNamespace". Traditionally, I went around this by simply passing 'this' to the callback as an extra parameter, but since I use socket.io, I can't just do it.

How can i solve this?

+3
source share
1 answer

You can wrap it in another function:

initialize: function() {
  // ...
  var client = this;
  this.socket.on('message', function(data) { client.on_message(data); });

In new browsers (or Node.js), you can also use a function in the prototype Functioncalled "bind":

  this.socket.on('message', this.on_message.bind(this));

"bind" , ( "on_message" ) this.

+9

All Articles