繁体   English   中英

除非采用简写形式,否则JavaScript回调方法不会更新AngularJS

[英]Javascript callback method not updating AngularJS unless in shorthand form

在以下嵌入在角度控制器中的两个片段中,用于登录用户(摘自angular-meteor教程 ):

    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的值,但是第二个片段不触发更新。 唯一的区别是在第一个方法中使用了速记方法声明。 这是什么原因呢?

这不只是速记方式 ,第一个使用箭头功能 箭头函数与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));
    };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM