我一直在试图弄清楚模板如何与模型和集合一起工作。部分教程有意义,但其他部分则没有。所以我一直在搞乱JSFiddle,试图让下面的例子起作用。
我真正想做的就是构建一些对象。然后将它们输出到特定div中的表中。
根据错误,几乎就好像数据没有传递到模板中一样。根据我的理解,我在做什么应该工作。
var Note = Backbone.Model.extend({
defaults : {
title: "",
description: ""
}
});
var note1 = new Note({title: "Patience", description: "Something we all need"});
var note2 = new Note({title: "Fun Times", description: "All the things"});
var Notebook = Backbone.Model.extend({
model: Note
});
notes = new Notebook([note1, note2]);
var NoteView = Backbone.View.extend({
el: '.content',
initialize: function() {
alert("hello");
this.render();
},
render: function () {
var template = _.template($('#notes-templates').html(), {notes: notes.models});
this.$el.html(template);
}
});
new NoteView();
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<div class="content">
</div>
<script type="text/template" id="notes-templates">
<table>
<thead>
<tr>
<th>title</th>
<th>scripture</th>
</tr>
</thead>
<tbody>
<% _.each(notes, function(note) { %>
<tr>
<td><%= note.get('title') %></td>
<td><%= note.get('description') %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
答案 0 :(得分:1)
尝试使Notebook
成为Backbone集合并使用集合api在视图中进行迭代。同时发布在http://jsfiddle.net/rossta/vn8hh5o7/2/
var Note = Backbone.Model.extend({
defaults : {
title: "",
description: ""
}
});
var note1 = new Note({title: "Patience", description: "Something we all need"});
var note2 = new Note({title: "Fun Times", description: "All the things"});
var Notebook = Backbone.Collection.extend({
model: Note
});
notes = new Notebook([note1, note2]);
var NoteView = Backbone.View.extend({
el: '.content',
initialize: function() {
alert("hello");
this.render();
},
render: function () {
var template = _.template($('#notes-templates').html(), {notes: notes});
this.$el.html(template);
}
});
new NoteView();
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<div class="content">
</div>
<script type="text/template" id="notes-templates">
<table>
<thead>
<tr>
<th>title</th>
<th>scripture</th>
</tr>
</thead>
<tbody>
<% notes.forEach(function(note) { %>
<tr>
<td><%= note.get('title') %></td>
<td><%= note.get('description') %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
&#13;