【问题标题】:EmberJS "this" changed in promise (find) callbackEmberJS "this" 在 promise (find) 回调中改变
【发布时间】:2014-04-23 13:48:35
【问题描述】:

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

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 回调中在控制器上设置“帐户”?

【问题讨论】:

    标签: javascript ember.js promise rsvp-promise


    【解决方案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);
        });
    
    },
    

    }

    修好了!添加了 .bind(this) :-)

    【讨论】:

      【解决方案2】:

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

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

      这里有一个链接可以帮助您理解这一点..

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

      我还建议观看 Crockford 的关于 Javascript 的视频,他解释了这一点以及您正在尝试做的事情的解决方法。

      这是他视频的链接..

      http://yuiblog.com/crockford/

      【讨论】:

        【解决方案3】:

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

        var self = this; 
        

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

        self.set('account', account);
        

        【讨论】:

        • 此方法不适用于 ember 对象。 var self = this; 会抛出错误。您需要像这样设置它self:this. 作为对象属性分配。但这不会让你到任何地方,因为无论如何你都需要使用“this”来引用它this.self
        猜你喜欢
        • 2017-06-23
        • 2016-03-26
        • 1970-01-01
        • 2017-06-17
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 1970-01-01
        • 2019-12-11
        相关资源
        最近更新 更多