Last Updated: February 25, 2016
·
1.854K
· igkuz

Fetching related models with Backbone

Backbone is a great framework, but it is as great as young. So, there are a lot of things that we don't get right out of the box. One of such things is getting the related models. Let me explain what I'm talking about.

Guess we have two models in Rails backend. Posts and Comments & Posts hasmany Comments_. Quite simple, but how we can get them from backbone?

That's the moment, when you're starting to shout different rude words and get angry. No support. There are several libs, provided by community like backbone-relational, there is also a very good tutorial about it, but for me it's too complex and do not work properly with coffeescript.

Stop talking - start coding.

The full code can be found at https://gist.github.com/4653259. There can be several syntax errors, but it's just for showing the scheme.

We have Posts (title, body). So on the index page we are loading only titles, and then when we need to show the full Post we fetch other information from the server.
We are putting our collection of Comments into the model's attribute

this.comments = new Comments(null, {
  baseUrl: this.url + this.id
});
this.on('change:body', function() {
  this.comments.fetch();
}, this);

Binding fetch() action of Comments on any change in the body attribute of the Post model(fetching from the server is also a change).

To my mind that's the key point of linking the models with each other. I do not claim on the correct version of traversing the relation, it's just the variant that helped me to solve the problem.

With the help of ant_ti.

1 Response
Add your response

Stop talking - start coding.

:)

over 1 year ago ·