我有一个嵌套的对象列表,而且我很难确定单个对象的目标。我有一个Items
的数组,每个数组都有许多Options
。现在,一个操作被我的(预期的)单数OptionController
捕获,但更改应用于所有选项。
那么,我如何只针对一个选项?
示例jsBin:http://jsbin.com/ONAsIpa/4/edit
模板:
<script type="text/x-handlebars" data-template-name="application">
<p><strong>Ember.js example:</strong><br> Finally, a dashboard that monitors 'items', & their child 'options'!!</p>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="items">
<h2>Items:</h2>
<dl>
{{#each}}
<dt>Item: {{title}}</dt>
<dd>Cost: {{cost}}</dd>
<dd class='options'>{{render 'options' options}}</dd>
{{/each}}
</dl>
</script>
<script type="text/x-handlebars" data-template-name="options">
<dl>
{{#each option in controller }}
{{render option}}
{{/each}}
</dl>
</script>
<script type="text/x-handlebars" data-template-name="option">
<dt>Option cost: {{option.cost}}</dt>
<dd {{bindAttr class=":opt-btn isSelected"}}{{action 'toggleOption'}}>Pick Me!</dd>
</script>
Ember对象:
App = Ember.Application.create();
/**** ROUTES ****/
App.Router.map(function() {
this.resource('items');
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('items');
}
});
App.ItemsRoute = Ember.Route.extend({
model: function() {
var a = Em.A();
a.pushObject( App.Item.create({title: 'A', cost: '100', options: buildMockOptions('A')}));
a.pushObject( App.Item.create({title: 'B', cost: '200', options: buildMockOptions('B')}));
a.pushObject( App.Item.create({title: 'C', cost: '300', options: buildMockOptions('C')}));
return a;
}
});
buildMockOptions = function(someVar){
var arr = [];
for(var i = 0;i<3;i++){
var opt = App.Option.create({someOption: 'Option for ' + someVar + ': ' + i});
opt.cost = 5*i;
arr.pushObject(opt);
}
return arr;
};
/**** MODELS ****/
App.Item = Ember.Object.extend({
title: '',
cost: '',
quantity: '',
options: null,
totalOptionsCost: function(){
var j = this.get('options').reduce(
function(prevValue, currentValue, index, array){
return prevValue + parseInt(currentValue.get('cost'), 10); }, 0);
return j;
}.property('options.@each.cost')
});
App.Option = Ember.Object.extend({
someOption: '',
cost: ''
});
/**** CONTROLLERS ****/
App.ItemsController = Ember.ArrayController.extend({
totalOptions: function(){
var opts = this.mapBy('options');
return [].concat.apply([], opts).length;
}.property(),
totalOptionCost: function(){
var sum = this.reduce(function(prev, curr){
return prev + curr.get('totalOptionsCost');},0);
return sum;
}.property('@each.totalOptionsCost'),
actions: {
toggleOption: function(opt) {
alert('ItemsController caught action');
}
}
});
App.OptionController = Ember.Controller.extend({
actions: {
toggleOption: function(opt) {
this.set('isSelected', !this.get('isSelected') );
alert('OptionController caught action');
}
}
});
选项控制器没有模型支持(因为它在扩展控制器)。这几乎就像是一个部分转换。因此,这主要是一个范围界定问题。
App.OptionController = Ember.ObjectController.extend({
{{render 'option' option}}
{{cost}} instead of {{option.cost}}
http://jsbin.com/OjOvarE/1/edit