在ember.js中访问模型之外的计算属性

Accessing computed properties outside of their model in ember.js

本文关键字:计算 属性 模型 ember js 访问      更新时间:2023-09-26

我有一个名为users.js的成员应用程序,该应用程序具有相关的控制器和路由。在我的usersController.js中,我有一个计算系统中用户数量的函数。然后,我可以在我的users模板中显示此图。然而,我想在我的index模板中显示这个数字,这可能吗?我该怎么做呢?现在这个数字似乎无法在我的users模型之外使用。

这是我的用户控制器-

App.UsersController = Ember.ArrayController.extend({
  sortProperties: ['name'],
  sortAscending: true,
numUsers: function() {
        return this.get('model.length');
    }.property('model.[]')
});

还有我的html-

  <script type = "text/x-handlebars" id = "index">
  <h2>Homepage</h2>
//This is where I would like the figure to be
  <h3>There are {{numUsers}} users </h3>  
    </script>
<script type = "text/x-handlebars" id = "users">
<div class="col-md-2">
{{#link-to "users.create"}}<button type="button" class="btn btn-default btn-lg"><span class="glyphicon glyphicon-plus"></button> {{/link-to}}
//This works fine
<div>Users: {{numUsers}}</div>
</div>
<div class="col-md-10">
  <ul class="list-group">
  {{#each user in controller}}
  <li class="list-group-item">
    {{#link-to "user" user}}
      {{user.name}}
    {{/link-to}}
  </li>
{{/each}}
</ul>
{{outlet}}
</div>
</script>

您只需在IndexRoute中加载所有用户,如下所示:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('user');
  }
});

并将共享逻辑(在这种情况下为用户计数)提取到一个mixin中,并在需要的地方使用:

App.UsersCountMixin = Ember.Mixin.create({
  numUsers: function() {
    return this.get('model.length');
  }.property('model.[]')
});
App.IndexController = Ember.ArrayController.extend(App.UsersCountMixin, {
});
App.UsersController = Ember.ArrayController.extend(App.UsersCountMixin, {
  sortProperties: ['name'],
  sortAscending: true
});

因此{{numUsers}}将在您的index模板中可用。

要与多个模型共享逻辑,您需要为model属性创建一些别名以避免歧义:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      users: this.store.find('user'),
      subjects: this.store.find('subject'),
    })
  }
});
App.UsersCountMixin = Ember.Mixin.create({
  users: Ember.required(),
  numUsers: function() {
    return this.get('users.length');
  }.property('users.[]')
});
App.SubjectsCountMixin = Ember.Mixin.create({
  subjects: Ember.required(),
  numSubjects: function() {
    return this.get('subjects.length');
  }.property('subjects.[]')
});
App.UsersController = Ember.ArrayController.extend(App.UsersCountMixin, {
  users: Ember.computed.alias('model'),
  sortProperties: ['name'],
  sortAscending: true
});
App.SubjectsController = Ember.ArrayController.extend(App.SubjectsCountMixin, {
  subjects: Ember.computed.alias('model'),
  sortProperties: ['name'],
  sortAscending: true
});
App.IndexController = Ember.ArrayController.extend(App.UsersCountMixin, App.SubjectsCountMixin, {});

当然,这是很多只显示数据长度的代码,因为你可以只使用:

<h3>There are {{users.length}} users </h3> 
<h3>There are {{subjects.length}} subjecst </h3> 

但我认为您将有更复杂的计算属性可供共享。在这种情况下,mixin是实现它的好方法。