Has anyone used ember-data to model a tree of data?
I would assume it would be something like:
Node = DS.Model.extend({
children: DS.hasMany(Node),
parent: DS.belongsTo(Node)
});
However, I have not been able to get this working which leads be to believe that either: 1) I'm just plain wrong in how I'm setting this up or, 2) it is not currently possible to model a tree using ember-data.
I'm hoping that it's the former and not the latter...
Of course it could be the JSON...I'm assuming the JSON should be of the form:
{
nodes: [
{ id: 1, children_ids: [2,3], parent_id: null },
{ id: 2, children_ids: [], parent_id: 1 },
{ id: 3, children_ids: [], parent_id: 1 }
]
}
Any tips/advice for this problem would be greatly appreciated.
There are several little things that prevent your fiddle to work:
the DS.hasMany
function asks for a String as argument. Don't forget the quotes: DS.hasMany('Node')
in the fixture definition, hasMany
relationships should not be postfixed by _ids
or anything. Just use the plain name. For instance: { id: 42, children: [2,3], parent_id: 17 }
the length
property of DS.ManyArray
should be accessed using the get
function: root.get('children.length')
by default, the fixture adapter simulates an ajax call. The find
query will populate the record after waiting for 50ms. In your fiddle, the root.get('children.length')
call comes too early. You can configure the fixture adapter so that it makes synchronous call:
App.store = DS.Store.create({
revision: 4,
adapter: DS.FixtureAdapter.create({
simulateRemoteResponse: false
})
});
Or you can load data to the store without any adapter:
App.store.loadMany(App.Node, [
{ id: 1, children: [2, 3] },
{ id: 2, children: [], parent_id: 1 },
{ id: 3, children: [], parent_id: 1 }
]);
and last one: it seems like the Ember app should be declared in the global scope (no var
), and Ember-data models should be declared in the app scope (replacing var Node = ...
by App.Node = ...
)
Full example:
App = Ember.Application.create();
App.store = DS.Store.create({
revision: 4
});
App.Node = DS.Model.extend({
children: DS.hasMany('App.Node'),
parent: DS.belongsTo('App.Node')
});
App.store.loadMany(App.Node, [
{ id: 1, children: [2, 3] },
{ id: 2, children: [], parent_id: 1 },
{ id: 3, children: [], parent_id: 1 }
]);
var root = App.store.find(App.Node, 1);
alert(root.get('children'));
alert(root.get('children.length'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With