【发布时间】:2014-05-04 22:01:23
【问题描述】:
我知道对此有一些问题,但答案对我来说不是很清楚。这就是为什么我再次问这个问题,以便我可以得到一个清晰而简单的答案。
我一直在 Backbone 中使用 Collection 时遇到问题,尤其是使用 JSON 数据填充它。
我似乎无法让集合在视图中呈现,即使在 firebug 中我可以看到它是从服务器获取的,但屏幕仍然是空的。
此外,当我执行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"
}
]
【问题讨论】:
-
我没有发现任何明显的问题。我建议你在
this.$el.append(this.template(caller.toJSON()));处设置一个断点。检查调用者是否正确,以及 caller.toJSON() 返回您认为应该返回的内容。验证 this.template 是否正确,$el 是否正确等 -
感谢@Neil 的回复。我刚刚在渲染函数中添加了一些
console.log以查看caller内部的内容,但似乎render甚至没有被应用。 -
您尝试遍历集合但实际上并未分配它,此外您使用的是 this.model 而不是 this.collection。
-
谢谢@Jack。我刚刚用你的建议更新了我的答案。但它仍然没有渲染任何东西,并且正在调用渲染函数。我认为问题比这更深,我无法弄清楚它是什么。另外你所说的集合没有分配是什么意思?
-
我发布了一个带有 jsbin 链接的答案,请注意我是手动添加数据并调用渲染函数而不是获取它,但它应该可以正常工作。
标签: javascript html json backbone.js model-view-controller