Here’s my code. Feel free to tell me what I’m doing wrong or right. I’m trying to store everything in the PhishVids object. If this is the wrong way to do things, please let me know.
My JSON is stored in /shows/YEAR.json. The years range from 1987-2011. I can’t seem to get the JSON loaded in, so can anyone point me in the right direction?
var PhishVids = {
Models: {
Show: Backbone.Model.extend({
defaults: {
showid: 'show id',
year: 'year',
month: 'month',
day: 'day',
venue: 'venue'
}
})
},
Views: {
Show: Backbone.View.extend({
el: $('#content'),
initialize: function() {
this.model.fetch();
this.model.bind('change', this.render, this);
},
render: function(event) {
var compiled_template = _.template($("#shows-template").html());
this.el.html(compiled_template(this.model.toJSON()));
return this; //recommended as this enables calls to be chained.
},
events: {
"click .show": "showClick"
},
showClick: function(event) {
}
})
},
Collections: {
ShowList: Backbone.Collection.extend({
parse: function(response) {
return response.items;
}
})
}
};
Show Template:
<script type="text/template" id="shows_template">
<a href='/<%= year %>/<%= month %>/<%= day %>' class='show <%= month %> <%= day %>' id='<%= showid %>'><%= month %>/<%= day %></a>
<div class='venue'><%= venue %></div>
</script>
I can see a few problems here. Without seeing the calling code, an example of your JSON, and knowing a bit more about what you are trying to do it’s impossible to know what you are actually doing. However, here are a few things I notice right off:
1) When you fetch a collection, the collection will create model instances out of the data it receives (which should be an array of objects). It will use this.model as the type, but you haven’t defined what model should be…
2) Neither your model nor your collection has either url or urlRoot members which would tell them how to fetch
3) In your view object, your initialize function (which is called right after the object is constructed) references this.model, which hasn’t been set anywhere and will therefore be undefined
Generally if you’re going to use something like this you should first instantiate the collection (new object()) and then call .fetch() to get the data. fetch() can either accept an object with success and error as callbacks or it returns a jquery deferred object (if you’re using jquery) that you can use .done(..) and .fail(..) to find out when it finished.
Then you can pass the model in as an option (part of an object) into the new …View({model: model_you_want}), etc, and use that to render.
Hope that helps