最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Original 'this' context with Socket.IO - Stack Overflow

programmeradmin3浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 10

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.

发布评论

评论列表(0)

  1. 暂无评论