By default, the urlRoot
property is not defined. This urlRoot
property is used by the url
method to create a relative URL where the model's resource would be located on the server.
var User = Backbone.Model.extend({
urlRoot: '/api/users',
// or
urlRoot: function () {
return '/api/users'
}
});
var user = new User();
The url
method will firstly check if the model's idAttribute
(defaulted at 'id') has been defined. If not, the model isNew
and url
will simply return the results of urlRoot
.
user.url() // /api/users
If the model's idAttribute
has been defined, url
will return the urlRoot
+ the model's idAttribute
user.set('id', 1);
user.url() // /api/users/1
Calling save
on a new model will result in a POST request to the results of url
var user = new User({ username: 'johngalt' });
user.save() // POST http://webroot/api/users
Calling save
on an existing model will result in a PUT request to the results of url
user.set('id', 1);
user.set('username', 'dagnytaggart');
user.save() // PUT http://webroot/api/users/1
Calling fetch
on an existing model will result in a GET request to the results of url
user.fetch() // GET http://webroot/api/users/1
Calling destroy
on an existing model will result in a DELETE request to the results of url
user.destroy() // DELETE http://webroot/api/users/1