Ember-Data template
by MikeAski
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.sortedItems"}}
</script>
<script type="text/x-handlebars" data-template-name="item">
{{view.indentation}} {{view.content.index}} – {{view.content.name}}
{{view App.ItemsView contentBinding="view.content.sortedItems"
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'} ),
sortedItems: function () {
var items = this.get('items').toArray();
return items.sort(function (lhs, rhs) {
return lhs.get('index') - rhs.get('index');
});
}.property('[email protected]')
});
App.Item = DS.Model.extend({
name: DS.attr('string'),
index: DS.attr('number'),
items: DS.hasMany('App.Item', {key: 'itemIds'} ),
item: DS.belongsTo('App.Item'),
product: DS.belongsTo('App.Product'),
sortedItems: function () {
var items = this.get('items').toArray();
console.log('>>', items);
return items.sort(function (lhs, rhs) {
return lhs.get('index') - rhs.get('index');
});
}.property('[email protected]')
});
App.Product.FIXTURES = [{
id: 1,
name: 'Product1',
itemIds: [2,3,6]
}];
App.Item.FIXTURES = [{
id: 2,
index: 1,
name: 'item 2 belongs to product',
itemIds: [4,5]
}, {
id: 3,
index: 0,
name: 'item 3 belongs to product',
itemIds: []
}, {
id: 4,
index: 1,
name: 'item 4 belongs to item 2',
itemIds: []
}, {
id: 5,
index: 0,
name: 'item 5 belongs to item 2',
itemIds: [7]
}, {
id: 6,
index: 2,
name: 'item 6 belongs to product',
itemIds: []
}, {
id: 7,
index: 0,
name: 'item 7 belongs to item 5',
itemIds: [8]
}, {
id: 8,
index: 0,
name: 'item 8 belongs to item 7',
itemIds: []
}];
App.productController = Ember.ObjectController.create({
content: App.store.find(App.Product, 1)
});
App.ItemsView = Ember.CollectionView.extend({
itemViewClass: Ember.View.extend({
templateName: 'item',
indentation: function () {
var indentation = this.get('parentView.indentation');
return Array(indentation).join(" ");
}.property('parentView.indentation'),
...