Ember-Data template
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script src="https://github.com/downloads/emberjs/ember.js/ember-latest.js"></script>
<script src="http://cloud.github.com/downloads/emberjs/data/ember-data-latest.js"></script>
<script type="text/x-handlebars">
{{App.productController.content.name}}
<br><br>
{{view App.ItemsView contentBinding="App.productController.sortedChildren"}}
</script>
<script type="text/x-handlebars" data-template-name="item">
{{view.indentation}} {{view.content.index}} – {{view.content.name}}
{{view App.ItemsView contentBinding="view.content.sortedChildren"
indentationBinding="view.childrenIndentation"}}
</script>
JavaScript
window.App = Ember.Application.create();
App.store = DS.Store.create({
revision: 4,
adapter: DS.fixtureAdapter
});
App.Product = DS.Model.extend({
name: DS.attr('string'),
items: DS.hasMany('App.Item', {key: 'itemIds'} ),
sortedIds: DS.attr('string', { key: 'sortedIds' }),
sortedChildren: function () {
if (!this.get('isLoaded')) {
return [];
}
var sortedIds = this.get('sortedIds').split(','),
items = this.get('items').toArray();
return sortedIds.map(function (id) {
if (id === '') {
return null;
}
return items.find(function (item) {
return item.get('id') == id;
});
}).filter(function(item) {
return !!item;
});
}.property('isLoaded', 'sortedIds', '[email protected]')
});
App.Item = DS.Model.extend({
name: DS.attr('string'),
items: DS.hasMany('App.Item', {key: 'itemIds'} ),
sortedIds: DS.attr('string', { key: 'sortedIds' }),
item: DS.belongsTo('App.Item'),
product: DS.belongsTo('App.Product'),
sortedChildren: function () {
if (!this.get('isLoaded')) {
return [];
}
var sortedIds = this.get('sortedIds').split(','),
items = this.get('items').toArray();
return sortedIds.map(function (id) {
if (id === '') {
return null;
}
return items.find(function (item) {
return item.get('id') == id;
});
}).filter(function(item) {
return !!item;
});
}.property('isLoaded', 'sortedIds', '[email protected]')
});
App.Product.FIXTURES = [{
id: 1,
name: 'Product1',
itemIds: [2,3,6],
sortedIds: '6,3,2'
}];
App.Item.FIXTURES = [{
id: 2,
name: 'item 2 belongs to product',
itemIds: [4,5],
sortedIds: '5,4'
}, {
id: 3,
name: 'item 3 belongs to product',
itemIds: [],
sortedIds: ''
}, {
id: 4,
name: 'item 4 belongs to item 2',
itemIds: [],
sortedIds: ''
}, {
id: 5,
name: 'item 5 belongs to item 2',
itemIds: [7],
sortedIds: '7'
}, {
id: 6,
...