余烬。js-这个。Set()in ApplicationRoute不工作
-
21-12-2019 - |
题
每当用户登录时,我正在尝试设置一个布尔变量。
App.ApplicationRoute = Ember.Route.extend({
isLoggedIn: false,
init: function() {
if (loggedIn) {
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
});
}
});
然而,在 this.set()
我得到:
未捕获的TypeError:undefined不是函数
有什么想法吗?
我认为处理用户会话的最佳位置是 App.ApplicationRoute
因为它是一切的根源。这会导致问题吗?
更新后的:这里的反馈是当前/完整的代码。
App.ApplicationRoute = Ember.Route.extend({
isLoggedIn: false,
init: function() {
this._super();
auth = new FirebaseSimpleLogin(appRef, function(error, user) {
if (user) {
console.log(user)
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
});
}
})
所以我以前遗漏了我的Firebase代码,因为我并不真正认为它相关,但是为了跟踪问题,我会将其添加进去。
解决方案
原因与
this
被错误地设置在你的firebasesimplelogin.您在构造函数内部使用的函数必须在外部上下文的'this'引用中传递。最简单的方法是将函数的代码更改为:
function(error, user) {
if (user) {
console.log(user)
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
}.bind(this));
其他提示
第一件事是第一件事:)
如在 余烬。js文档化:
注意事项:如果你确实重写了像Ember这样的框架类的init。查看或余烬。ArrayController, 一定要叫这个。Init声明中的_super()!如果你不这样做,Ember可能没有机会做重要的设置工作,你会在你的应用程序中看到奇怪的行为。
第二,你的 loggedIn
变量没有声明也没有实例化,因此null以及您的 error
但我想你只是扯出你的项目的一些代码来摆弄一个快速的例子,所以如果你这样做:
App.ApplicationRoute = Ember.Route.extend({
isLoggedIn: false,
init: function() {
this._super(); // <-- call `this._super()` here
if (loggedIn) {
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
});
}
});
一切都应该按预期工作:)
不隶属于 StackOverflow