【问题标题】:Javascript callback method not updating AngularJS unless in shorthand formJavascript 回调方法不更新 AngularJS,除非是速记形式
【发布时间】:2016-02-09 09:41:44
【问题描述】:

以下两个 sn-ps 嵌入在用于登录用户的角度控制器中(取自 angular-meteor tutorial):

    this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, (err) => {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        });
    };

和:

    this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        });
    };

第一个导致 AngularJS 在回调后更新 error 的值,但第二个 sn-p 不会触发更新。唯一的区别是在第一个中使用了速记方法声明。这是什么原因?

【问题讨论】:

  • 请问脚本你是如何调用这个函数的?

标签: javascript angularjs meteor methods shorthand


【解决方案1】:

这不仅仅是速记,第一个使用arrow function。箭头函数处理其作用域的方式与 function lambda 不同。

箭头函数继承其父作用域。所以,不需要在里面绑定this(本例)。

如果你使用function lambda,你必须bind this

this.login = function() {
        Meteor.loginWithPassword(this.credentials.email, this.credentials.password, function(err) {
            if (err) {
                this.error = err.reason;
            }
            else {
                $state.go('index');
            }
        }.bind(this));
    };

【讨论】:

    猜你喜欢
    • 2015-08-23
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多