我有這張表,其中包含名爲書籍的數組中的項目列表。即從HTML中動態更改Backbone.js中的集合的大小選擇表格
var books = [
{"title": "Harry Potter 1", "author": "J. K. Rowling"},
{"title": "Harry Potter 2", "author": "J. K. Rowling"}
//.... More books
]
我分開我的觀點是單爲書一行,該被渲染成表全書列表,同時還爲選擇形式的圖的圖。
var Book = Backbone.Model.extend({});
var BooksCollection = Backbone.Collection.extend({
model: Book
});
var Books = new BooksCollection(books);
//
var SelectView = Backbone.View.extend({
el: ".container",
events: {
"change #num-entries": "updateBookList"
},
initialize: function() {
this.render();
},
render: function() {
this.collection.models.length = $('#num-entries').val();
},
updateBookList: function() {
this.collection.models.length = $('#num-entries').val();
//console.log(this.collections.models.length);
booksview.$el.empty();
booksview.unbind();
booksview.render();
}
});
var selectView = new SelectView({
model: Book,
collection: Books
});
//
var BooksView = Backbone.View.extend({
type: "BooksView",
el: "#books-table",
initialize: function() {
//this.collection.models.length = $('#num-entries').val();
this.render();
},
render: function() {
this.collection.each(function(book) {
var bookView = new BookView({
model: book
});
bookView.render();
this.$el.append(bookView.$el);
}, this)
}
});
var BookView = Backbone.View.extend({
type: "BookView",
className: 'book',
tagName: 'tr',
template: _.template($("#books-template").html()),
events: {
"click .delete": "bookRemove"
},
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
bookRemove: function(book) {
this.remove();
this.model.trigger('destroy', this.model);
//Books.remove(book);
},
});
var booksview = new BooksView({
collection: Books
})
這是我的HTML
<div class="container">
<div class="form-group" id="entries-per-page">
<label>Number of Entries:</label>
<select class="form-control" id="num-entries">
<option value="10">Show 10 entries</option>
<option value="25" selected>Show 25 entries</option>
<option value="50">Show 50 entries</option>
<option value="100">Show 100 entries</option>
</select>
</div>
<table class="table table-bordered table-hover">
<thead>
<tr class="header-names">
<th class="book-category">Title</th>
<th class="book-category">Author</th>
<th class="book-category">Meta Data</th>
<th class="book-category">Options</th>
</tr>
</thead>
<tbody id="books-table">
<script type="text/template" id="books-template">
<td><%- title %></td>
<td><%- author %></td>
<td><span class='glyphicon glyphicon-remove delete'></span></td>
</script>
</tbody>
</table>
</div>
目前我的選擇視圖可以使列表集合收縮亂碼(所以我的表從25項變爲10例),但是如果我嘗試使表顯示更多的書我得到一個錯誤 - 未捕獲TypeError:無法讀取未定義的屬性'toJSON'。我會認爲使用collection.slice函數應該有所幫助,但我無法弄清楚。此外,讓我的刪除書功能與此工作很難。我可以使用切片方法獲得任何幫助,以動態更改我的書籍數組或書籍集合的大小,以便表格正確顯示?