问题
I have a item model and each item can have many items. This can be many levels deep.
I have this jsfiddle http://jsfiddle.net/rmossuk/xmcBf/3/
how do I change this to be able to have multiple levels of items and also how do I loop down each level to display them ?
I also need be able to order each items children and store that order to persist to server.
please can anyone show me how you can do this ?
UPDATE:
I have now managed to implement the Items can be many levels deep bit of this problem see here http://jsfiddle.net/rmossuk/fBmmS/3/
But i need a way to state the order of each items children and to display them in that order. At the moment it just displays the children items from the itemIds array but this is only used for association purposes and i cant change this to re-order can i ??
Anyone know how to do this ?
Thanks a lot rick
回答1:
In the views, use a sortedItems
computed property, defined as follow:.
JS
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();
return items.sort(function (lhs, rhs) {
return lhs.get('index') - rhs.get('index');
});
}.property('items.@each.isLoaded')
});
See a full working solution here: http://jsfiddle.net/MikeAski/K286Q/3/
EDIT
According to your request, here is another solution, keeping the sorted ids inside the parent (to minimize updates & indexes management): http://jsfiddle.net/MikeAski/K286Q/12/
JS
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', 'items.@each.isLoaded')
});
A little bit more complicated, nevertheless...
来源:https://stackoverflow.com/questions/11767446/ember-js-order-hasmany-children