EmberJS "this"在承诺(查找)回调中更改



当我想在控制器操作中从服务器获取帐户时,例如:

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);
        });
    },
}

它抛出一个错误,因为this.set('account', account)线上的"this"不再是控制器。我现在如何从这个promise回调中在控制器上设置"帐户"?

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);
    });
},

}

修复它!added.bind(this):-)

这不是EmberJS所做的,这只是Javascript作用域的工作方式。

this关键字的作用域是在其中使用它的函数。

这里有一个链接可以帮助你理解这一点。。

http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/

我还建议看Crockford在Javascript上的视频,他解释了这一点以及你想要做的事情的解决方法

这是他的视频链接。。

http://yuiblog.com/crockford/

一种解决方案是使用典型的

var self = this; 

在进入更改this范围的函数并在函数中使用self而不是this之前。

self.set('account', account);

最新更新