Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fetch a single model in Backbone?

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?

like image 851
James A. Rosen Avatar asked Feb 23 '11 21:02

James A. Rosen


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is a model backbone?

Model. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.

What is Backbone used for?

Backbone is known for being lightweight, as its only hard dependency is on one JavaScript library, Underscore. js, plus jQuery for use of the full library. It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized.


1 Answers

Try specifying urlRoot in the model:

From the docs:

var Book = Backbone.Model.extend({urlRoot : '/books'}); var solaris = new Book({id: "1083-lem-solaris"}); solaris.fetch(); 
like image 169
Hernan S. Avatar answered Oct 06 '22 01:10

Hernan S.