我知道有關於這個問題的幾個問題,但答案並不是非常明確,我可以實現。這就是爲什麼我再次問這個問題,所以我可以有一個清晰而簡單的答案。Backbone:集合在View中不呈現,即使它被提取
我一直在Backbone的Collection
遇到問題,特別是使用JSON數據填充它。
我似乎無法得到集合呈現在視圖中,即使在螢火蟲我可以看到,它是從服務器獲取,但屏幕仍然是空的。 另外,當我做一個console.log('callers: ', this.callerList)
時,它返回一個包含models=[0]
的對象。但是當我展開該對象時,models
充滿了來自JSON文件的數據。 Backbone發生了什麼,這是令人困惑的結果?
有人可以請向我解釋如何做到這一點?我一直在和這個爭鬥多年,我無法理解它。
非常感謝
JS:
(function($, window) {
// model
var CallerModel = Backbone.Model.extend({});
// collection
var CallersList = Backbone.Collection.extend({
model: CallerModel,
url: 'js/json/callers.json'
});
// view
var CallerView = Backbone.View.extend({
el: '.caller-app',
template: _.template($('#callers-template').html()),
initialize: function() {
this.callerList = new CallersList();
this.callerList.fetch();
this.callerList.bind('reset', this.render);
console.log('caller: ', this.callerList);
},
render: function(e) {
console.log('RENDER');
_.each(this.collection.models, function(caller) {
this.$el.append(this.template(caller.toJSON()));
console.log('callerList: ', caller);
}, this);
return this;
}
});
// start
var callerView = new CallerView();
}(jQuery, window));
HTML:
<!-- wrapper -->
<div class="wrapper">
<h1>Missed Calls App</h1>
<div class="caller-app"></div>
</div>
<!-- wrapper -->
<!-- templates -->
<script type="text/template" id="callers-template">
<div class="caller">
<h2><%= title %> <%= name %> called</h2>
<h3>From <%= agency %></h3>
<p>When: <%= when %></p>
<p>Contact: <%= tel %></p>
<p>Says:"<%= message %>"</p>
</div>
</script>
<!-- templates -->
JSON:
[
{
"id": 1,
"title": "Mrs",
"name": "Mui",
"agency": "Ryuzanpaku Dojo",
"when": "evening",
"tel": "0207 123 45 67",
"message": "Check your availability"
},
{
"id": 2,
"title": "Mrs",
"name": "Shigure",
"agency": "Ryuzanpaku Dojo",
"when": "evening",
"tel": "0207 123 45 67",
"message": "Check your availability"
}
]
我沒有看到任何明顯的問題。我建議你在這個點上放一個斷點。$ el.append(this.template(caller.toJSON()));'。檢查調用者是否正確,並且該caller.toJSON()返回您認爲應該的內容。驗證this.template是否正確,$ el是否正確等。 – Neil
Thanks @Neil for respond。我在render函數中添加了一些'console.log'來查看'caller'裏面的內容,但是好像'render'甚至沒有被應用。 – Shaoz
您試圖遍歷集合,但您尚未實際分配它,此外您正在使用this.model而不是this.collection。 – Jack