【发布时间】:2015-08-15 14:17:59
【问题描述】:
调用此 $http 请求后(使用server.refresh();)
MinecraftServer.prototype.refresh = function(){
return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);
}
这个函数的this是window对象,而不是MinecraftServer对象:
MinecraftServer.prototype.acceptData = function(data){
data = data.data
if(data && data.online){
this.online = data.online;
//do more stuff
} else { // do more stuff }
}
因此,MinecraftServer 对象不会更新其属性,而是window 会获取属性。
如果这有帮助,这是我的工厂代码:
.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;
})
【问题讨论】:
-
您可能想了解更多关于how this works in JavaScript 的信息。它肯定会帮助您更好地理解。
-
@fstanis - 非常感谢!这对我有很大帮助。
标签: javascript angularjs factory angularjs-factory