Ember.js - this.set() in ApplicationRoute not working
-
21-12-2019 - |
Question
I am trying to set a boolean variable whenever the user is logged in.
App.ApplicationRoute = Ember.Route.extend({
isLoggedIn: false,
init: function() {
if (loggedIn) {
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
});
}
});
However, on this.set()
I get:
Uncaught TypeError: undefined is not a function
Any ideas?
I figured that the best place to handle user session is in the App.ApplicationRoute
since its the root of everything. Does this cause a problem?
UPDATED: With feedback here is the current / full code.
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);
}
});
}
})
So I left out my Firebase code previously because I didnt really think it relevant, but for the sake of tracking down the problem, I'll add it in.
Solution
The reason has to do with the
this
being wrongly set in your firebasesimplelogin. The function you are using inside the constructor must be passed in a reference to 'this' of the outer context. The easiest way to do it is by changing the code of the function to this:
function(error, user) {
if (user) {
console.log(user)
this.set('isLoggedIn', true);
} else {
console.log(error)
this.set('isLoggedIn', false);
}
}.bind(this));
OTHER TIPS
First thing's first :)
As stated at the Ember.js documenation:
NOTE: If you do override init for a framework class like Ember.View or Ember.ArrayController, be sure to call this._super() in your init declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application.
Second, your loggedIn
variable is not declared nor instantiated and therefore null as well as your error
but I guess you just ripped out some code of your project to fiddle together a quick example, so if you do:
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);
}
});
}
});
everything should work as expected :)