如何设置Ember控制器属性

5

我正在查看一个Ember应用程序的应用模板,它使用条件检查来确定显示哪些链接。

{{#if isAuthenticated}}
    link
{{else}}
    link...
{{/if}}

根据用户是否注册/登录,isAuthenticated属性会有条件地设置

App.AuthController = Ember.ObjectController.extend({
    currentUser: null,
    isAuthenticated: Em.computed.notEmpty("currentUser.email"),
    login: function(route) {
      var me;
      me = this;
      return $.ajax({
        url: "/users/sign_in.json",
        type: "POST",
        data: {
          "user[email]": route.currentModel.email,
          "user[password]": route.currentModel.password
        },
        success: function(data) {

          me.set('currentUser', data.user);

         return route.transitionTo('user', data.user);

该应用程序可以顺利处理注册和登录,但是应用程序模板始终显示未经过身份验证的用户链接。根据此处所见的代码,是否存在某些原因导致 isAuthenticated 在登录后没有更新?

1
你说你的handlebars片段来自application模板,但是你的控制器名为App.AuthController。因此,你的模板没有连接到你的控制器。相反,你的应用程序模板正在向ApplicationController实例请求isAuthenticated。而这个属性不存在,因此返回false。 - mavilein
@mavilein 谢谢,有没有办法从AuthController中设置ApplicationController的属性? - BrainLikeADullPencil
1
在您的ApplicationController中,指定needs:["auth"]。然后,您可以通过controllers.auth.isAuthenticated访问它。 - chopper
1个回答

8

如果 @mavilein 和 @chopper 允许我发表一个明确的答案来完全回答这个问题,那么就是这样:

ApplicationController

由于你的 ApplicationController 是支持你的应用程序模板的,你应该使用 needs API 来要求 AuthController,如下所示:

App.ApplicationController = Ember.ObjectController.extend({
  needs: ['auth']
  ...
});

应用模板

然后,您可以通过在访问时前缀为controllers.auth来访问所有AuthController的属性。因此,在您的应用程序模板中,您可以这样做:

{{#if controllers.auth.isAuthenticated}}
  link
{{else}}
  link...
{{/if}}

如果您不喜欢这个长名称,也有一个缩写:

 App.ApplicationController = Ember.ObjectController.extend({
  needs: ['auth'],
  isAuthenticated: Ember.computed.alias('controllers.auth.isAuthenticated')
  ...
});

这样做后,您可以在应用程序模板中轻松执行以下操作:
{{#if isAuthenticated}}
  link
{{else}}
  link...
{{/if}}

在这种情况下,isAuthenticated属性是指代原始控制器AuthController计算得出的ApplicationController。希望能对您有所帮助。

2
您始终可以像往常一样发布出色的答案 :-) - mavilein

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接