Ember.js: Reloading .hasMany Relationships Passed Through "Links" in the Payload

Let's say I have two models, Topic and Post :

 App.Topic = DS.Model.extend({ posts: DS.hasMany('post', { async: true, inverse: 'post' }); }); App.Post = DS.Model.extend({ topic: DS.belongsTo('topic', { async: true }); }); 

hasMany Theme Messages and the message belongsTo a Topic.

To load data from the API, one initial call is made (which selects the topic ... topic ID 2, for example): GET /topics/2

After receiving the payload for this GET request, the serializer then adds the links key to the payload. This has a way to download messages related to the topic:

 "topic": { "id": 2, "links": { "posts": "/topics/2/posts" } } 

This second request (before /topics/2/posts ) is how posts are downloaded and attached to the topic.

All this works great the first time the page loads.

The problem occurs when Post is created during a page session . Although I can get this theme to reload (by calling .reload() on the model object that represents the theme), the Posts associated with the theme do not reload. The second API call (to receive messages) is never made, while the first call (to receive only the topic) is made. If I refresh the page, the messages created by me on the previous page load will be downloaded (but, of course, if I go over and make a few more messages, they will not appear until the next page loads).

Looking for a solution, I came across this question: How to reload asMynchronous communication with hasMany links?

However, it seems that the solution no longer works for current versions of Ember / Ember-Data. Provided by JSFiddle does not work.

So, how can I reload this kind of hasMany relationship? Any help is appreciated.

+52
javascript ember-data
May 19 '14 at 1:53
source share
2 answers

So, there is a problem with GitHub that is not closed yet (today): https://github.com/emberjs/data/issues/1913

I don’t know how to make it reboot, but I thought that I would share the workaround that I made to solve this problem.

I use websockets, so when a new message is ever created, I just send it through websocket and use the data to update the collection.

I know that this does not fix the problem with Ember Reload, but I think this is a decent solution for people who already use Websockets / Socket.io.

+1
Nov 24 '14 at 15:34
source share
 DS.Model.reopen({ reloadLink: function (linkKey) { if ($.isArray(linkKey)) { var promises = []; for (var i = 0; i < linkKey.length; i++) { promises.push(this.reloadLink(linkKey[i])); } return Em.RSVP.all(promises); } else { var rel = this._relationships[linkKey]; if (rel) { if (rel.reload) { return rel.reload(); } else if (rel.fetchLink) { return rel.fetchLink(); } } } } }); 

Example:

 model: function () { var model = this.modelFor('_some_model_'); return model.reloadLink(['link1', 'link2']).then(function () { return model; }); } 
+1
Mar 25 '15 at 9:20
source share



All Articles