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

时间:2013-12-16 11:56:12

标签: javascript ember.js

我有一个带有名为users.js的模型的ember应用程序,其中包含相关的控制器和路由。在我的usersController.js中,我有一个计算系统中用户数的函数。然后,我可以在users模板中显示此图。但是,我想在我的index模板中显示该数字,这可能吗?我该怎么做 - 现在这个图似乎不能在users模型之外使用。

这是我的usersController -

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>

1 个答案:

答案 0 :(得分:1)

您只需加载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> 

但我认为你将拥有更复杂的计算属性来分享。在这种情况下,mixins是实现它的好方法。