Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class property in a callback function

Tags:

javascript

I got a little problem in my code. Here it is :

// We are in the constructor of my class
this.socket.emit('getmap', {name: name}, function(data){
    this.mapData = data.map;
    this.load();
});

The problem is that the mapData attribute isn't set, in fact, this refers to the namespace Socket. How can I access to this.mapData through this function ?

And sorry for my bad english ...

like image 640
DarkChipolata Avatar asked Dec 09 '22 15:12

DarkChipolata


2 Answers

You need to save a reference to the this object. Inside the callback thiswill refer to the object on which the function has been called. A common pattern is this:

// We are in the constructor of my class
var self = this;
this.socket.emit('getmap', {name: name}, function(data){
    self.mapData = data.map;
    self.load();
});
like image 136
Kenneth Avatar answered Dec 11 '22 08:12

Kenneth


You have to be aware of how JavaScript determines the value of this. In anonymous functions like the one you're using, it's usually the global namespace or window object on the web. In any case, I would just suggest you take advantage of the closure and use a variable in your constructor.

// We are in the constructor of my class
var _this = this;
this.socket.emit('getmap', {name: name}, function(data){
    _this.mapData = data.map;
    _this.load();
});
like image 26
Aaron Gibralter Avatar answered Dec 11 '22 08:12

Aaron Gibralter