如何设置Ember控制器属性

Bra*_*cil 5 ember.js

我正在查看的Ember应用程序的应用程序模板使用条件检查来确定要显示的链接

{{#if isAuthenticated}}
    link
{{else}}
    link...
{{/if}}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

该应用程序能够毫无问题地处理注册和登录,但是,应用程序模板始终显示用户未经过身份验证的链接.是否有一些理由为什么isAuthenticated在登录时不会根据您在此处看到的代码进行更新?

int*_*xel 8

如果@mavilein和@chopper允许我发布一个确定的答案来完全覆盖这个问题,那么它在这里:

ApplicationController的

由于您ApplicationController是备份应用程序模板的人,因此您应该AuthController使用以下needsAPI:

App.ApplicationController = Ember.ObjectController.extend({
  needs: ['auth']
  ...
});
Run Code Online (Sandbox Code Playgroud)

应用模板

然后,您可以访问AuthController前缀为访问权限的所有属性controllers.auth,因此在您的应用程序模板中,您可以执行以下操作:

{{#if controllers.auth.isAuthenticated}}
  link
{{else}}
  link...
{{/if}}
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢长名称,还有一个快捷方式:

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

这样,您可以在应用程序模板中执行以下操作:

{{#if isAuthenticated}}
  link
{{else}}
  link...
{{/if}}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它指的ApplicationController isAuthenticated是从始发控制器计算的属性AuthController.

希望能帮助到你.

  • 你总是被允许像往常一样发布一个很棒的答案:-) (2认同)