Pregunta

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.

¿Fue útil?

Solución 2

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'

Otros consejos

You have to set the urlRoot not url and Backbone will add the id to the end of your url :

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

There are two points you need to validate:

  1. Model use urlRoot as rest API url, but Collection use url.
  2. Output result in the fetch success callback

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

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

    //It is safe to output result in success callback which guarantee the api is called user.fetch({success: function(){ console.log(user.get('screenname')); }});

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top