這很可能是最好使用嵌套視圖解決。你可以看到my jsFiddle here。
我不認爲這是一個非常複雜的方法,但如果您有任何關於設計的問題,請讓我知道。
把手:
<script type="text/x-handlebars">
{{#each App.countriesController}}
{{view Ember.Checkbox titleBinding="name" valueBinding="isChecked"}}
{{/each}}
<hr />
{{#each App.countriesController}}
{{#if isChecked}}
{{view App.PartsByCountryView contentBinding="this" partsListBinding="App.partsController"}} <br />
{{/if}}
{{/each}}
</script>
<script type="text/x-handlebars" data-template-name="selected-country">
Country: {{content.name}} <br />
Parts:
{{#each filteredParts}}
{{name}}
{{/each}}
</script>
應用代碼:
window.App = App = Ember.Application.create();
/**************************
* Models
**************************/
App.Country = Ember.Object.extend({
id: null,
name: "",
isChecked: null
});
App.Part = Ember.Object.extend({
id: null,
name: "",
countryId: null
});
/**************************
* Views
**************************/
App.PartsByCountryView = Ember.View.extend({
content: null,
partsList: null,
templateName: 'selected-country',
filteredParts: function() {
return this.get("partsList").filterProperty('countryId', this.getPath('content.id'))
}.property('[email protected]').cacheable()
});
/**************************
* Controllers
**************************/
App.set('countriesController', Ember.ArrayController.create({
content: Ember.A()
}));
App.set('partsController', Ember.ArrayController.create({
content: Ember.A()
}));
/**************************
* App Logic
**************************/
$(function() {
App.get('countriesController').pushObjects([
App.Country.create({id: 1, name: "USA"}),
App.Country.create({id: 2, name: "UK"}),
App.Country.create({id: 3, name: "FR"})
]);
App.get('partsController').pushObjects([
App.Part.create({id: 1, name: "part1", countryId: 1}),
App.Part.create({id: 2, name: "part2", countryId: 1}),
App.Part.create({id: 3, name: "part3", countryId: 1}),
App.Part.create({id: 4, name: "part4", countryId: 2}),
App.Part.create({id: 5, name: "part5", countryId: 2}),
App.Part.create({id: 6, name: "part6", countryId: 2}),
App.Part.create({id: 7, name: "part7", countryId: 2}),
App.Part.create({id: 8, name: "part8", countryId: 3}),
App.Part.create({id: 9, name: "part9", countryId: 3}),
App.Part.create({id: 10, name: "part10", countryId: 3}),
App.Part.create({id: 11, name: "part11", countryId: 3})
]);
});
嗨羅伊謝謝你的偉大答案。只有一個問題:如果我轉到控制檯並嘗試添加另一部分像這樣'App.get('partsController')。pushObjects(App.Part.create({id:999,name:「part999」,countryId: 2})]); '我如何將它添加到相關部分而不必點擊複選框並再次打開?再次感謝 – 2012-03-06 13:50:04
對不起,我忘了添加一個屬性來觀察我的filteredParts計算屬性的定義。我更新了代碼和jsFiddle。這個成功地回答了你的問題嗎? – 2012-03-06 13:57:38
哇,非常快,非常感謝你,是的,這已經完全解答了我的問題。 – 2012-03-06 14:02:53