18

I have a list of items and clicking on them should bring to user details on it (another view). In my router I have such a route for this:

'details/:id'   :   'details',

Now, in details function I should fetch my object (Fetching will trigger new view rendering). But what should i do so that backbone attach item id to model.url? 2 ways i have for now is:

Create url on the fly when fetching:

this.realty_object.fetch({url: SITE_PATH + 'blah/blah/' + id});

And something like this:

this.realty_object
    .set({id : id}, {silent: true})
    .fetch();

But I have doubts that it is right solutions. How it should be? What is the difference between model.urlRoot and model.url().

SET001
  • 11,480
  • 6
  • 52
  • 76

2 Answers2

35

The right answer is using urlRoot property of model. If it is set up, models id will be appended to this url while fetching. So it may look like this (objects have different names from what is in my first post but idea is the same - fetch single model by id):

Group = Backbone.Model.extend({
    urlRoot: SITE_PATH + 'group/index',
});

And in route:

this.group = new Group({id: id});
this.group.fetch();
justinhj
  • 11,147
  • 11
  • 58
  • 104
SET001
  • 11,480
  • 6
  • 52
  • 76
  • 2
    This is ok unless you want to keep the model instance intact, but just move it between blank and populated states (eg: a logged in/logged out user). In that case, the best solution I can find is the OP's `.set` of the id with `silent:true`. – SimplGy May 23 '13 at 17:24
  • You should also pass `silent: true` to the options hash of the model constructor to avoid the model being marked as dirty on fetch: `this.group = new Group({id: id}, {silent: true});` – Burgi Mar 16 '14 at 20:53
0

take a look over here, it explains perfectly well what one of the better solutions is for fetching single models

you'd use a function for putting together the url, as a model property. using the .isNew() at least this is how i've been doing it for a while now, i believe it's better than building a url in the fetch every time you need something.

How do I fetch a single model in Backbone?

Community
  • 1
  • 1
Sander
  • 13,301
  • 15
  • 72
  • 97