问题
When I want to fetch an account from the server in an controller action e.g:
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?
回答1:
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) :-)
回答2:
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..
http://yuiblog.com/crockford/
回答3:
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);
来源:https://stackoverflow.com/questions/23246373/emberjs-this-changed-in-promise-find-callback