So I've managed to figure out how to populate my collection from an external file, and render a view based on a url, but I'm running into a problem. The code below is working as intended, except on page load, I'm getting the following error:
Uncaught TypeError: Cannot call method 'get' of undefined
Getting rid of "view.render()" eliminates the error, but now the app no longer responds to ID changes in the url (e.g. going from #/donuts/1 to #/donuts/2 does not update the view)
Could someone point me in the right direction here?
The Code:
(function(){
var Donut = Backbone.Model.extend({
defaults: {
name: null,
sprinkles: null,
cream_filled: null
}
});
var Donuts = Backbone.Collection.extend({
url: 'json.json',
model: Donut,
initialize: function() {
this.fetch();
}
})
var donuts = new Donuts();
var donutView = Backbone.View.extend({
initialize: function() {
this.collection.bind("reset", this.render, this)
},
render: function() {
console.log(this.collection.models[this.id].get('name'))
}
});
var App = Backbone.Router.extend({
routes: {
"donut/:id" : 'donutName',
},
donutName: function(id) {
var view = new donutView({
collection: donuts,
id: id
});
view.render();
}
});
var app = new App();
Backbone.history.start();
})(jQuery);
The JSON:
[
{
"name": "Boston Cream",
"sprinkles" : "false",
"cream_filled": "true"
},
{
"name": "Plain",
"sprinkles": "false",
"cream_filled": "false"
},
{
"name": "Sprinkles",
"sprinkles": "true",
"cream_filled": "false"
}
]