Search code examples
javascriptrestbackbone.js

Backbone fetch not working with single model


Here is my backbone code:

var UserModel=Backbone.Model.extend({
  url: 'http://api.myapi.com/user'
});

var user=new UserModel();
user.set({id:1});
user.fetch();
console.log(user.get('screenname'));

This returns the whole collection of users instead of user with the id of 1. When I change the url to

url: 'http://api.myapi.com/user/1'

I get back the user that I want. Why don't I get the record for 'user 1' when I user.set({id:1});

Note - My API is at a different domain, that is why I have the entire URL in my url property. Please help, I am ready to give up on backbone.


Solution

  • You will need to add the id to your model url like so.

    url: function() {
     if(this.id) {
       return 'http://api.myapi.com/user/' + this.id;
     } 
    
     return 'http://api.myapi.com/user';
    }
    

    And then when you instantiate the user model you can pass it an id like this.

    var user = new UserModel({id: 1});
    

    Then when you do user.fetch() it will get 'http://api.myapi.com/user/1'

    Also by not passing an id to UserModel Backbone will send a POST request to 'http://api.myapi.com/user'