I'm just starting to play around with Backbone. I've got a view associated with a collection, and I want to render the view when the collection successfully syncs with the server.
I've managed to get my collection to sync successfully -
var MyCollection = Backbone.Collection.extend({
model: Backbone.Model,
url: '/api/cart/lineitem'
});
var myCollection = new MyCollection();
myCollection.fetch({
success: function() {
console.log('fetched ' + myCollection.length + ' objects');
}
});
The console shows that the fetch function works.
However I'm getting some strange behaviour in my view. I can't seem to get the render function to run.
var MyView = Backbone.View.extend({
el: $('#mini_cart'),
cartTpl: _.template($('#miniCartTemplate').html()),
initialize: function() {
this.listenTo(this.collection, 'reset', this.render);
this.listenTo(this.collection, 'reset', console.log('collection reset'));
},
render: function(){
console.log('rendering MyView');
}
});
var myView = new MyView({
collection: new MyCollection()
});
The console shows that the event fires but it never enters into the render
method (ie I get the 'collection reset' message but never the 'rendering MyView' message). I don't really understand what's going on (I don't really see how the reset
event is being fired on my collection at all).