When I want to fetch an account from the server in an controller action eg:
account: false,
actions: {
// When the oAuth popup returns this method will be called
fetchUser: function(id)
{
// Get the account from the server
this.store.find('account', id).then(function(account)
{
this.set('account', account);
}, function(error)
{
console.log('error', error);
});
},
}
It throws an error because "this" on the line this.set('account', account)
is no longer the controller. How can I set "account" on the controller now from within this promise callback?
account: false,
actions: {
// When the oAuth popup returns this method will be called
fetchUser: function(id)
{
// Get the account from the server
this.store.find('account', id).then(function(account)
{
this.set('account', account);
}.bind(this), function(error)
{
console.log('error', error);
});
},
}
Fixed it! added .bind(this) :-)
That is not EmberJS doing that, that's just the way Javascript scopes work.
The this
keyword's scope is the function in which it is used.
Here's a link that will help you understand this..
http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
I also suggest watching Crockford's videos on Javascript, he explains this and the workaround for what you're trying to do.
Here's a link to his videos..
One solution is to use the typical
var self = this;
Before entering the function that changes the scope of this
and using self
instead of this
from within the function.
self.set('account', account);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.