Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emberjs Data How to load hasMany-Data later

I have the following Emberjs Data model:

App.File = DS.Model.extend({
  like: DS.attr('boolean'),
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.extend({
  file: DS.belongsTo('App.File'),
  comment: DS.attr('string')
});

And preload it with:

 App.store.load(App.File, {id: 1, like: false});

Now I thought, if I get the comments like this:

var f = App.store.find(App.File, 1);
var c = f.get("comments");

var c is a empty EmberArray and a request is send to the server. But I don't get a request? Why and how do I have to do it? I really don't wanna preload the comments.

Further more, if I add a comment, but also change the file simultaneously:

f.get("comments").createRecord({comment: "test"});
f.set("like", true);
App.store.commit();

Two requests are send to the server. But if I then return the following JSON (for the file):

{ "id": 1, like: true }

My first visible comment disappears again. Why? And what do I have to do?

Thanks for your help!

like image 342
lüku Avatar asked Sep 11 '12 07:09

lüku


1 Answers

Regarding the first part of your question: You should populate the comments ids in the file's data:

App.store.load(App.File, {id: 1, like: false, comments: [1, 2, 3]});

So the comments will be lazy loaded when needed.

Regarding the second part: You certainly do not serialize the comment ids on the reply from your server, so the comments are reset, as you describe an empty comments list.

You should at least return the comments ids as shown just before... The two issues are linked.

like image 164
Mike Aski Avatar answered Sep 19 '22 17:09

Mike Aski