在父视图中,我传递了骨干模型的一部分(该模型称为库,因此我将Library.book
对象作为this.book
传递。当我警告{{1它看起来像:
this.book
我有一个骨干视图,如下所示:
{"favoritePages":["384","383","385"],"summariesOfFavoritePages":["Cool","Great","Informative"]}
传递模型的库视图(父视图)部分如下所示:
var LibraryBookView = Backbone.View.extend({
initialize: function(options) {
if (options) {
_.extend(this, options);
}
},
render: function () {
// FOR TESTING
alert(JSON.stringify(this.book));
var that = this;
$(".test").on('click', function(e) {
var id = $(this).data("id");
var pagesIndex = $.inArray( id + "", that.book.favoritePages );
that.book.favoritePages[pagesIndex] = "DELETED"; // BASICALLY WHAT I WANT TO DO WITH BACKONE'S SET
});
}
});
基本上,我想用var LibraryView = Backbone.View.extend({
initialize: function(options) {
if (options) {
_.extend(this, options);
}
this.render();
_.each(this.model.get("library").books, function(book){
var libraryBookView = new LibraryBookView({
el: $('.content'),
book: book,
model: this.model
});
libraryBookView.render();
});
},
更新this.book
,但不确定如何在书籍迭代中使用数组?
答案 0 :(得分:4)
我可以想到几个解决方案:
if(this.model.get('library')。books [this.bookIndex]!= undefined)
this.model.get('library')。books [this.bookIndex] = this.book;
book
在所有library.books
属性中都是唯一的。var book = _.findWhere(this.model.get("library").books, this.book); if(book != undefined) book = this.book;
答案 1 :(得分:2)
您还可以尝试记住LibraryBookView中的书籍索引。
_.each(this.model.get("library").books, function(book, bookIndex){
var libraryBookView = new LibraryBookView({
el: $('.content'),
book: book,
bookIndex: bookIndex,
model: this.model
});
libraryBookView.render();
});
然后在您的图书馆图书课程中,您要设置模型:
this.model.set('library.books[' + this.bookIndex + ']', this.book);
这假设您的图书索引不会发生变化......如果他们这样做了,那么您将不得不更新每个图书馆图书视图的索引,或者做其他事情。