0

After calling this $http request (with server.refresh();)

MinecraftServer.prototype.refresh = function(){
    return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);
}

This function's this is the window object, instead of the MinecraftServer object:

MinecraftServer.prototype.acceptData = function(data){
    data = data.data

    if(data && data.online){
        this.online = data.online;
        //do more stuff       
    } else { // do more stuff }
}

So instead of the MinecraftServer object getting it's attributes updated, the window gets the attributes.

In case this will help, here is my abriged factory code:

.factory('MinecraftServer',function($http){
    function MinecraftServer(name, ip) { //does stuff }

    MinecraftServer.prototype.acceptData = function(data){
        data = data.data

        if(data && data.online){
            this.online = data.online;
            //do more stuff       
        } else { // do more stuff }
    }
    MinecraftServer.prototype.refresh = function(){return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);}
    MinecraftServer.build = function(name, ip){return new MinecraftServer(name, ip)};
    return MinecraftServer;
})
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
  • 5
    You might want to read more about [how *this* works in JavaScript](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). It'll definitely help you get a better understanding. – fstanis Aug 15 '15 at 14:21
  • @fstanis - Thanks so much! That helped me a bunch. – Ben Aubin Aug 15 '15 at 14:30

1 Answers1

5

this as a callback is using some other this.

Use .bind:

return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData.bind(this));
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445