我嘗試this教程。一個簡單的例子 - Backbone.js教程 - 基於JSON + Collection的視圖
的HTML
是(的index.html):在瀏覽器中顯示
{
{
"name" : "AAAA",
"title" : "BBBB",
"background" : "CCCC"
},
{
"name" : "DDDD",
"title" : "EEEE",
"background" : "FFFF"
},
{
"name" : "GGGG",
"title" : "HHHH",
"background" : "IIII"
}
}
但沒有:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery.js"></script>
<script src="json2.min.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script>
$(function() {
var Profile = Backbone.Model.extend();
var ProfileList = Backbone.Collection.extend({
model: Profile,
url: 'jsonSample.json'
});
var ProfileView = Backbone.View.extend({
el: "#profiles",
template: _.template($('#profileTemplate').html()),
render: function (eventName) {
_.each(this.model.models, function (profile) {
var profileTemplate = this.template(profile.toJSON());
$(this.el).append(profileTemplate);
}, this);
return this;
}
});
var profiles = new ProfileList();
var profilesView = new ProfileView({ model: profiles });
profiles.fetch();
profiles.bind('reset', function() {
profilesView.render();
});
});
</script>
<title>Fortified Studio</title>
</head>
<body>
<div id="profiles"></div>
<script id="profileTemplate" type="text/template">
<div class="profile">
<div class="info">
<div class="name">
<%= name %>
</div>
<div class="title">
<%= title %>
</div>
<div class="background">
<%= background %>
</div>
</div>
</div>
</script>
</body>
</html>
jsonSample.json。這裏有什麼問題?
我對骨幹沒有太多的經驗,但是你的JSON文件裏面包含了一個哈希值和其他哈希值,不應該是一個包含哈希值的數組嗎? – htatche
@htatche:你說得對,現在json文件格式正確,但我仍然有同樣的問題。 – URL87
另外,一旦你解決這個問題,你需要打印一個集合,所以你必須遍歷它像'事端<%_.each(項目函數(項目,重點,編曲){<%= item %>}); %>' – htatche