nhaa123
nhaa123

Reputation: 9798

Out of scope in function callback

My client "class" looks like this:

var Client = (function () {
    function Client(socket)
    {
        this.socket = socket;
        this.country_code = null;

        var that = this;

        this.socket.on('message', function(data) {
            var r = JSON.parse(data);

            switch (r.action) {
                case 'init':
                    that.country_code = r.country_code;

                    break;
            }
        });
    }

    Client.prototype.message_handler = function(data)
    {
    };

    return Client;
})();

I'm utilizing websocket.io module to receive messages from clients. Now, the code above works, but I would really like to have the Client.prototype.message_handler, so that the ctor would look like this:

function Client(socket)
{
    this.socket = socket;
    this.country_code = null;

    this.socket.on('message', this.message_handler);
}

However, the problem is that now in the message_handler function

Client.prototype.message_handler = function(data)
{
    var r = JSON.parse(data);

    switch (r.action) {
        case 'init':
            this.country_code = r.country_code; // Doesn't work.

            break;
    }
};

this doesn't resolve to the Client-class. Is there anyway to pass or whatever this to the function via this.socket.on('message', this.message_handler)? That way, I could use inheritance with different handlers.

Upvotes: 0

Views: 82

Answers (1)

disatisfieddinosaur
disatisfieddinosaur

Reputation: 1550

Use the Javascript Function.prototype.bind feature described here. In your case, you can do this (updated thanks to @nhaa123's fix):

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

Then the socket's message handler will always be bound to the Client instance.

Upvotes: 1

Related Questions