user1354743
user1354743

Reputation: 417

Javascript bind and this

I am building a time measuring for the Websocket connection. I need to bind the open scope to to the server Object. But I also have the time1 which is the time from start to finish the connection. I wanted to put the time1 to the Object, which works fine but I dont have any acces to it in the bind function.

for(var i = 0; i < 10; i++) {
    Server[i] = new WebSocket('ws://127.0.0.1:9300');
    var time1 = new Date;
    Server[i].time1 = time1;

    Server[i].bind('open', function() {
                        var time2 = new Date;
                        /*** doesn't work ***/
                        console.log(time2 - this.time1);
                        /*** doesn't work ***/
                        console.log(time2 - Server[i].time1)
                        /***  ***/
    });
}

I tried these two ways both didn't work. I know that this in the bind is different but can someone tell me a way to secure each time 1 to each server[i] Object and then get acces to it in this bind method?

Thanks!

UPDATE *

Could you also tell how to change this function so it works correctly

this.conn.onopen = function(){dispatch('open',null)}

    var dispatch = function(event_name, message){
        var chain = callbacks[event_name];
        if(typeof chain == 'undefined') return; // no callbacks for this event
        for(var i = 0; i < chain.length; i++){
            chain[i]( message )
        }
    }

Upvotes: 1

Views: 228

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173532

You have to close over the value of i like so:

Server[i].bind('open', function(i) {
    return function() {
      var time2 = new Date;
      console.log(time2 - Server[i].time1)
    }
}(i));

Otherwise all your functions keep referencing the same variable.

Upvotes: 2

Related Questions