我有这个表,其中包含一个名为books的数组中的项目列表。即。
parseInt()
我将我的观点分成了一个书行的视图,整个书籍列表被渲染成一个表格,还有一个选择表格的视图。
var books = [
{"title": "Harry Potter 1", "author": "J. K. Rowling"},
{"title": "Harry Potter 2", "author": "J. K. Rowling"}
//.... More books
]
这是我的html
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
})
目前我的选择视图的杂乱代码可以使列表集合缩小(例如我的表从25个条目变为10个)但是如果我尝试让表格显示更多的书籍我会收到错误 - 未捕获的TypeError:无法读取未定义的属性'toJSON'。我认为使用collection.slice函数应该会有所帮助,但我无法弄明白。另外,让我的删除书功能使用它很难。我可以使用切片方法动态更改我的图书数组或图书集的大小,以便表格正确显示吗?
答案 0 :(得分:0)
当您直接修改模型数组时,您将丢失对模型的引用,并且您必须重新添加到集合以再次显示它们。
您应该在render方法中选择您需要的那些,而不是更改实际的集合。这在概念层面上也更有意义,因为要显示的条目数是一个视图关注点而不是数据关注点。
您的观点现在看起来像这样:
A
然后在var BooksView = Backbone.View.extend({
type: "BooksView",
el: "#books-table",
// Define how many books we want to display
booksToShow: 25,
initialize: function() {
this.render();
},
render: function() {
_.each(this.collection.slice(0, this.booksToShow), this.renderBook, this);
},
renderBook: function(bookModel) {
var bookView = new BookView({
model: book
});
bookView.render();
this.$el.append(bookView.$el);
}
});
内你可以打电话
updateBookList
另一件事;为了好的措施,你应该记得在删除它们时解除个别this.collection.booksToShow = $('#num-entries').val();
的绑定。最好通过在BookView
中创建一个方法来清理。