I have a Clock
model in Backbone:
var Clock = Backbone.Model.extend({});
I'm trying to get an instance of that that has the latest information from /clocks/123
. Some things I've tried:
a "class"-level method
Clock.fetch(123)
// TypeError: Object function (){ ... } has no method 'fetch'
creating an instance and then calling fetch
on it:
c = new Clock({id: 123})
c.fetch()
// Error: A 'url' property or function must be specified
a collection
I tried creating an AllClocks
collection resource (even though I have no use for such a thing on the page):
var AllClocks = Backbone.Collection.extend({
model: Clock,
url: '/clocks/'
});
var allClocks = new AllClocks();
allClocks.fetch(123);
// returns everything from /clocks/
How do I just get one API-backed Clock?
Your second approach is the approach I have used. Try adding the following to your Clock model:
This approach assumes that you have implemented controllers with the hashbang in your URL like so, http://www.mydomain.com/#clocks/123 , but it should work even if you haven't yet.
I personally recommend, following the Model#url method documentation
in your collection remember to add the collection url:
and in your View's initialize function do:
this way backbone will do an ajax request using this url:
your model will be updated and the view rendered, without modifying Collection#url or Model#urlRoot
note: sorry this example came out in coffee script, but you can easily translate it to js adding var statements
As a result you make a Ajax request on the
and you have the JSON response back.
Enjoiiii !!!
...and do this if you don't want the trailing slash on the model urlRoot:
I want to use RESTful url,but I couldn't understand why 'postId' can't be added to base url.
Then I know only after I set 'idAttribute' as 'postId' in Model can I get the right url. like this:
Try specifying urlRoot in the model:
From the docs: