I’m very new to Backbone.js (but not really to Django). I’ve set up a simple application to play around with backbone.js and Django (via djangorestframework), but I cannot seem to load server data into a collection.
Here’s the views.py
from djangorestframework.mixins import ResponseMixin
from djangorestframework.renderers import DEFAULT_RENDERERS
from djangorestframework.compat import View
from djangorestframework.response import Response
class WeekView(ResponseMixin, View):
"""Gets and returns specific week, or current week if no week data provided."""
renderers = DEFAULT_RENDERERS
def get(self, request):
response = Response(200, [{'day': x} for x in range(7)])
return self.render(response)
Here’s the backbone.js code:
$(document).ready(function() {
/* Backbone scripts */
var Day = Backbone.Model.extend({
});
var Week = Backbone.Collection.extend({
model: Day,
url: '/week'
});
var days = new Week;
days.fetch();
days.each(function(day) {
console.log(day.get("day"));
});
});
The console returns nothing.
If I log the days variable itself, I get something like:
> d
_byCid: Object
_byId: Object
length: 7
models: Array[7]
__proto__: x
The view seems to be OK (calling /week returns a nicely formatted list of dictionaries of the type {‘day’: number}.
I’m sure the solution to preloading simple data into a collection is a very simple one, but I’m stumped…
Thanks in advance!
Data is fetched asynchronously, so you need to respond to an event (like ‘reset’) or use a jquery deferred functionality (assuming jquery is used for the requests):
Or