Emberjs Data How to load hasMany-Data later

做~自己de王妃 提交于 2019-12-10 03:41:35

问题


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!


回答1:


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.




回答2:


It looks like part of the answer to this is to use the DS.Adapter.findAssociation(...) method in your adapter. However, I'm having the same problem as you when the parent record is loaded again from the server--all the child records get zapped.

I've posted my own question to see if I can get this sorted out. If that question gets answered, it will probably also be the answer to yours.



来源:https://stackoverflow.com/questions/12364734/emberjs-data-how-to-load-hasmany-data-later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!