I'm working on a Backbone.js project and I'm prettey confused about collection.on or so called binding.
Here's a bit of the code from my View.
initialize: function(){
this.accCollection = this.options.accCollection;
//Nothing shows without this line, which renders 3 times
this.accCollection.on('all', this.render, this);
this.accCollection.fetch({
success:function(){
this.render;
}
});
},
render: function(){
$('.currentPage').html("<h3>Accounts</h3>");
console.log(this.accCollection.models);
//Render it in jade template
this.$el.html(this.template({accCollection:this.accCollection.models}));
return this;
}
So the thing i don't understand is why without this line it wont work. It works if I use on with 'all' and with 'add'. Is it something with my fetch which causes it to not render empty data first time and on the second on third it works because it has been filled up then? Confused!
this.accCollection.on('all', this.render, this);
Tell me if I need to provide with more info and i'll edit the question!
/Regards
A couple things:
this.listenTo
(example below): this makes sure that events get undelegated when the view gets destroyed.success
callback does not share the view's context.this
in your callback refers to theoptions
object you're passing in, not the view or even the collection.What you probably want to do is this: