【问题标题】:Ember.js - this.set() in ApplicationRoute not workingEmber.js - ApplicationRoute 中的 this.set() 不起作用
【发布时间】:2014-05-25 23:19:52
【问题描述】:

每当用户登录时,我都会尝试设置一个布尔变量。

App.ApplicationRoute = Ember.Route.extend({
  isLoggedIn: false,

  init: function() {
      if (loggedIn) {
        this.set('isLoggedIn', true);
      } else {
        console.log(error)
        this.set('isLoggedIn', false);
      }
    });
  }
});

但是,在this.set() 我得到:

Uncaught TypeError: undefined is not a function

有什么想法吗?

我认为处理用户会话的最佳位置是App.ApplicationRoute,因为它是一切的根源。这会导致问题吗?

更新: 这里有反馈是当前/完整的代码。

App.ApplicationRoute = Ember.Route.extend({
  isLoggedIn: false,

  init: function() {
    this._super();

    auth = new FirebaseSimpleLogin(appRef, function(error, user) {
      if (user) {
        console.log(user)
        this.set('isLoggedIn', true);
      } else {
        console.log(error)
        this.set('isLoggedIn', false);
      }
    });
  }
})

所以我之前遗漏了我的 Firebase 代码,因为我认为它并不相关,但为了追查问题,我将其添加进去。

【问题讨论】:

    标签: javascript ember.js firebase


    【解决方案1】:

    原因与

    有关
    this
    

    在您的 firebasesimpllogin 中设置错误。您在构造函数中使用的函数必须在对外部上下文的“this”的引用中传递。最简单的方法是将函数的代码更改为:

    function(error, user) {
      if (user) {
        console.log(user)
        this.set('isLoggedIn', true);
      } else {
        console.log(error)
        this.set('isLoggedIn', false);
      }
    }.bind(this));
    

    【讨论】:

    • 不是真的:)。当涉及到如何设置内部函数的 this 值时,JS 语言的设计就搞砸了。我过去遇到了太多麻烦,所以当我发现诸如“未定义不是函数”之类的错误消息时,我首先检查的是......
    • 好电话。我把那个放在我的工具带上。
    【解决方案2】:

    第一件事是第一:)

    Ember.js documenation所述:

    注意:如果您确实为 Ember.View 或 Ember.ArrayController 等框架类重写 init,请务必在您的 init 声明中调用 this._super()!如果您不这样做,Ember 可能没有机会进行重要的设置工作,并且您会在应用程序中看到奇怪的行为。

    其次,您的 loggedIn 变量未声明或实例化,因此与您的 error 一样为 null 但我猜您只是撕掉了项目的一些代码来整理一个简单的示例,所以如果您这样做:

    App.ApplicationRoute = Ember.Route.extend({
      isLoggedIn: false,
    
      init: function() {
          this._super(); // <-- call `this._super()` here
    
          if (loggedIn) {
            this.set('isLoggedIn', true);
          } else {
            console.log(error)
            this.set('isLoggedIn', false);
          }
        });
      }
    });
    

    一切都应该按预期工作:)

    【讨论】:

    • 所以,首先,感谢您的回答!我忘了this._super()。其次,我用完整的代码更新了问题。我正在使用 Firebase,只是将其删除,因为我认为它不相关(猜得好!)但我不妨将其添加进去。我尝试了上面的内容,但它仍然无法正常工作。它会注销user,但会在this.set() 上返回错误
    • 刚刚看到它,但是使用您更新的代码,这一切都很有意义:) - 这是一个范围问题:)
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多