Reputation: 8993
I have a computed property cookieToggle
that I'm using in a LoginController. The basic idea is that it would observe the username
and rememberMe
fields and set or clear the username cookie as appropriate. Unfortunately when I update either of the dependant fields it never calls the cookieToggle
function (as observed by the lack of the console message that every call should produce). My main question is: why not? My secondary question is: is this a reasonable use of Ember's computed property?
App.LoginController = Ember.ObjectController.extend({
CLIENT_ID: 1,
username: null,
password: null,
rememberMe: false,
cookieToggle: function() {
var rememberMe = this.get('rememberMe');
var username = this.get('username');
console.log("cookie toggle");
if (rememberMe) {
$.cookie('auth_username', username);
} else {
$.removeCookie('auth_username');
}
return rememberMe;
}.property('rememberMe','username'),
init: function() {
this._super();
if ($.cookie('auth_username')) {
this.set('username', $.cookie('auth_username'));
this.set('rememberMe', true);
}
},
loginUser: function() {
var router = this.get('target');
var data = this.getProperties('username', 'password', 'rememberMe');
var user = this.get('model');
$.post('/api/oauth/user_credentials', { username: data.username, password: data.password, client_id: this.get('CLIENT_ID') }, function(results) {
// App.AuthManager.authenticate(results.api_key.access_token, results.api_key.user_id);
console.log(results);
$.cookie('auth_user', results.user.id);
router.transitionTo('users/login');
});
}
});
Upvotes: 1
Views: 3785
Reputation: 11668
A computed property is not the right decision in this case. You want to use an Observer
. You even use this verb yourself, right? :-) Just change your declaration from property
to observes
:
cookieToggle: function() {
var rememberMe = this.get('rememberMe');
var username = this.get('username');
console.log("cookie toggle");
if (rememberMe) {
$.cookie('auth_username', username);
} else {
$.removeCookie('auth_username');
}
}.observes('rememberMe','username') // will fire every time when one of those properties change
Upvotes: 3