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

Ember.js: How to represent a has-many model relationship?

本文关键字:一个 模型 关系 js 何表示 表示 Ember      更新时间:2023-09-26

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

在上一篇文章中,我得到了一个仪表板的工作示例,该仪表板监视单个项目集合
如何更新以表示每个项目的子选项

Javascript-来自jsBin(更新)

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>

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

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