问题
I am trying to set up an ember app where I have many Items, all of which have many Options. I then need a 'dashboard' area where I can monitor information on all Items/Options.
In a previous post I got a working example of a dashboard which monitors a single collection of Items.
How do I update this to represent child Options for each Item?
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')
});
Handlebars
<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:
Upfront, I would recommend using a clientside record management framework like ember data/ember model, they are a bit of a learning curve, but very awesome in the long run. If you don't want to do that, you can follow the same pattern you've already established with creating models.
http://jsbin.com/IpEfOwA/3/edit
来源:https://stackoverflow.com/questions/20078113/ember-js-how-to-represent-a-has-many-model-relationship