我注意到我的视图的渲染函数被调用了 2 次。这是我的代码:
视图,它是一个集合:
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;
});
app.js 中的代码,当我尝试显示时
var spots = new Spots({model: Spot});
window.counter = 0 + 0;
var spots_view = new SpotsView({collection: spots});
$('#spots').html(spots_view.render().el);
我的输出是:
inside render for the 1 times!
1
inside render for the 2 times!
6
在玩不同的东西时,我注意到它甚至被调用了 3 次。我究竟做错了什么?显然,当结果从服务器带到渲染函数时,这一行:
$('#spots').html(spots_view.render().el);
已经过去了
多谢