【问题标题】:Set controller property inside callback在回调中设置控制器属性
【发布时间】:2013-03-15 05:28:16
【问题描述】:

我有以下控制器使用ember.js 和ember-auth gem。这个控制器可以工作,但每次我登录时它都会设置loginErrorproperty。

BaseApp.SignInController = Auth.SignInController.extend({
  email: null,
  password: null,
  loginError: false,
  signIn: function() {
    this.registerRedirect();
    Auth.signIn({
      email: this.get('email'),
      password: this.get('password')
    });
    this.set('loginError', true); // Sets correctly but each time
    Auth.on('signInError', function() {
      console.log("This is a signin error");
    });
  }
});

显然,我想做的是在Auth.on 调用的函数内将loginError 设置为true,如下所示:

BaseApp.SignInController = Auth.SignInController.extend({
  email: null,
  password: null,
  loginError: false,
  signIn: function() {
    this.registerRedirect();
    Auth.signIn({
      email: this.get('email'),
      password: this.get('password')
    });
    Auth.on('signInError', function() {
      this.set('loginError', true); // Doesn't set the controller's property
      console.log("This is a signin error");
    });
  }
});

但这显然不起作用,因为回调内部的范围不同。也许我错过了一些非常基本的东西。我怎样才能让它发挥作用?

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    您传递给on 方法的匿名函数中的上下文(即this)与控制器中的上下文不同。您可以通过将上下文保存到闭包中的不同变量来解决此问题。

    var self = this;
    Auth.on('signInError', function() {
      self.set('loginError', true); // Should now set the controller's property
      console.log("This is a signin error");
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2013-02-28
    相关资源
    最近更新 更多