ビューのレンダリング関数が 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);
すでに過ぎた
どうもありがとう