Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching a single Backbone model from server

Say I have a route setup:

'photos/:id' : 'showPhoto'

and somebody shares the url: www.mysite.com/photos/12345 with a friend.

When their friend clicks on the shared link, showPhoto gets called back with 12345 passed as the id. I cant figure out how to fetch the model from the server, because even when setting its id property and calling fetch(), backbone thinks that the model isNew and so the ajax request url is just /photos instead of /photos/12345:

showPhoto: (id) ->
  photo = new models.Photo _id:id
  photo.fetch #does a GET to /photos, I would have expected it to request /photos/12345
    success: () ->
      render photo view etc...

Photo = Backbone.Model.extend
  idAttribute: '_id'
  urlRoot: '/photos'

The model Photo is usually part of a collection, but in this scenario someone is visiting the site directly and only expects to see data for one photo, so the collection is not instantiated in this state of the app.

Is the solution to load the entire collection of photos and then use collection.getById(id)? This just seems way too inefficient when I just want to load the properties for one model.

like image 978
cjroebuck Avatar asked Sep 12 '11 00:09

cjroebuck


Video Answer


1 Answers

if you don't have the model as part of a collection, you have to tell the model the full url manually. it won't auto-append the id to the urlRoot that you've specified. you can specify a function as the urlRoot to do this:

Photo = Backbone.Model.extend({
  urlRoot: function(){
    if (this.isNew()){
      return "/photos";
    } else {
      return "/photos/" + this.id;
    }
  }
});

Backbone uses the id of the model to determine if it's new or not, so once you set that, this code should work correctly. if it doesn't, you could always check for an id in the if-statement instead of checking isNew.

like image 185
Derick Bailey Avatar answered Sep 29 '22 03:09

Derick Bailey