I've noticed that my view's render function is being called 2 times. Here's my code:
the View, which get's a collection:
define([
'jquery',
'underscore',
'backbone',
'mustache',
'icanhaz',
'views/spots/Spot',
'collections/Spots',
'text!../../../../templates/spots/spots.mustache!strip',
], function($,
_,
Backbone,
mustache,
ich,
SpotView,
Spots,
SpotsTemplate){
var SpotsView = Backbone.View.extend({
initialize: function(){
var ich = window['ich'],
spots = ich.addTemplate('spots',SpotsTemplate);
spots = ich['spots'];
this.template = spots;
_.bindAll(this,'render');
var self = this;
this.collection.bind("all", function() { self.render(); }, this);
this.collection.fetch();
},
events: {
"change": "render"
},
render: function(){
window.counter = window.counter +1;
console.log('inside render for the ' + window.counter + ' times!');
this.el = this.template();
this.collection.each(function (spot) {
$(this.el).append(new SpotView({model:spot}).render().el);
}, this);
console.log($(this.el).children().length);
return this;
}
});
// Returning instantiated views can be quite useful for having "state"
return SpotsView;
});
the code inside app.js , when i try to display
var spots = new Spots({model: Spot});
window.counter = 0 + 0;
var spots_view = new SpotsView({collection: spots});
$('#spots').html(spots_view.render().el);
My output is:
inside render for the 1 times!
1
inside render for the 2 times!
6
while playing with different things ive noticed it is being called 3 times even. What am i doing wrong? obviously by the time the results are brought from the server to the render function this line:
$('#spots').html(spots_view.render().el);
has already passed
thanks a lot