EmberJS “this” changed in promise (find) callback

自古美人都是妖i 提交于 2019-12-13 19:13:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!