[Answered ]-Backbone Collection

2👍

When you call fetch on your collection, it makes an AJAX request to:

 http://backbonejs-beginner.herokuapp.com/books

However, there is no API set up there. Either one of two things needs to happen:

1) you need to modify your code to point to a different URL, one that does have an existing API (perhaps whatever tutorial you are using has such an API)

2) you need to create such an API yourself on yoursever.com (and then make your Backbone code point to that API’s URL instead)

Without a server to support it, operations like save and fetch and such in Backbone simply cannot function.

As a side note, Django is a web site framework. While you can use it to create server-side APIs, that’s not really Django’s focus. Because of this, several good third party libraries exist for doing RESTful APIs (ie. the kind that Backbone likes) in Django; personally I’d recommend either Django REST Framework (I use it and it works great) or TastyPie (never used it, but it’s very popular).

0👍

When using a backbone collection you need to return a json array of objects from your api url (http://backbonejs-beginner.herokuapp.com/books)
Example

{[{"name":"bookname", "publisher": "penguin"}, {"name":"bookname", "publisher":"penguin"}]}

You’ll also want a model for your collection. A model would look like this
Example:

var Book = Backbone.Model.extend({
defaults: {
"name":  "",
"publisher": ""
}
});

The way that the collection works is by parsing the json array and turning each object in the array in to a model that you specific (in this instant an individual book with values for the name and publisher).

When you make a .fetch() on your model you are making a GET request, so make sure that your http://backbonejs-beginner.herokuapp.com/books url is prepared to receive GET requests and respond with the json data in the format I specified up top.

Leave a comment