Search code examples
javascriptangularjsfactoryangularjs-factory

Javascript `this` statement not working


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;
})

Solution

  • 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));