Ember.js:如何表示一个有很多模型的关系?

时间:2013-11-19 17:30:43

标签: javascript ember.js relationship

我正在尝试设置一个ember应用程序,其中有很多项目,所有项目都有很多选项。然后我需要一个“仪表板”区域,我可以监控所有项目/选项的信息。

a previous post中,我得到了一个监控单个项目集合的仪表板的实例 如何更新此项以表示每个项目的子选项?

Javascript - from jsBin (updated)

App = Ember.Application.create();

/* ROUTES */
App.Router.map(function() {
  this.resource('items');
  this.resource('dashboard');
});
App.IndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('items');
  }
});
App.ItemsRoute = Ember.Route.extend({
  model: function() {
    var a = Em.A();
    a.pushObject( App.Items.create({title: 'A', cost: '100'}));
    a.pushObject( App.Items.create({title: 'B', cost: '200'}));
    a.pushObject( App.Items.create({title: 'C', cost: '300'}));
    return a;
  }
});

/* MODELS */
App.Items = Ember.Object.extend({
  title: '',
  cost: '',
  quantity: ''
});


/* CONTROLLERS */
App.ItemsController = Ember.ArrayController.extend({
  legend: 'test',
  len: function(){
    return this.get('length');
  }.property('length'),
  totalCost: function() {
    return this.reduce( function(prevCost, cost){
      return parseInt(cost.get('cost'),10) + (prevCost || 0);
    });
  }.property('@each.cost')
});
App.DashboardController = Em.Controller.extend({
  needs: ['items'],
  itemsLength: Ember.computed.alias('controllers.items.len'),
  itemsTotalCost: Ember.computed.alias('controllers.items.totalCost')  
});

车把

 <script type="text/x-handlebars" data-template-name="application">
  <p><strong>Ember.js example</strong><br>Using an a dashboard that monitors 'items'.</p>
    {{render dashboard}}
    {{outlet}}
  </script>

  <script type="text/x-handlebars" data-template-name="items">
    <h2>Items:</h2>
    <dl>
      {{#each}}
        <dt>Title: {{title}}</dt>
        <dd>Cost: {{cost}} {{input value=cost}}</dd>
      {{/each}}
    </dl>
  </script>

  <script type="text/x-handlebars" data-template-name="dashboard">
    <h2>Overview:</h2>
    {{#if controllers.items}}
    <p>Total number of items (expect 3): {{itemsLength}}<br>
    Total cost of items (expect 600): {{itemsTotalCost}}</p>
    {{/if}}
  </script>

1 个答案:

答案 0 :(得分:2)

Upfront,我建议使用像ember data / ember模型这样的客户端记录管理框架,它们有点学习曲线,但从长远来看非常棒。如果您不想这样做,您可以按照您已经建立的相同模式创建模型。

http://jsbin.com/IpEfOwA/3/edit