I’m new to backbone and handlebars.js. I’m trying to programmatically add a new Item to a collection, and I’d like backbone to render the collection using Render.
What am I doing wrong?
var Item = Backbone.Model.extend({
defaults: {
}
});
var List = Backbone.Collection.extend({
model: Item
});
var ListView = Backbone.View.extend({
el: $('BODY'), // el attaches to existing element
initialize: function () {
_.bindAll(this, 'render'); // every function that uses 'this' as the current object should be in here
this.collection = new List();
this.render();
},
render: function () {
var template = Handlebars.compile($('#screenshot_template').html());
$(this.el).html(template({
row: this.collection
}));
return this;
}
});
var listView = new ListView();
window.screenshots = listView;
window.screenshots.collection.add({
myurl: 'http://placehold.it/350x150'
});
My handlebars template looks like:
<script id="screenshot_template" type="text/x-handlebars-template">
{{#each row}}
<div><img src="{{this.myurl}}"></div>
{{/each }}
</script>
Add a listener to your view so it knows when the collection is firing the add event – usually done in the initialize function of your view:
Obviously you’ll want to add it after you’ve instantiated your collection.