在迭代时设置对象

时间:2014-08-03 01:55:32

标签: javascript jquery backbone.js underscore.js

在父视图中,我传递了骨干模型的一部分(该模型称为库,因此我将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,但不确定如何在书籍迭代中使用数组?

2 个答案:

答案 0 :(得分:4)

我可以想到几个解决方案:

  • 与@Lochemage建议相同。使用bookIndex,但假设书籍索引不会改变。为了设置模型,我建议如下:
  

if(this.model.get('library')。books [this.bookIndex]!= undefined)
     this.model.get('library')。books [this.bookIndex] = this.book;

  • 使用Underscore库的findWhere方法。假设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);

这假设您的图书索引不会发生变化......如果他们这样做了,那么您将不得不更新每个图书馆图书视图的索引,或者做其他事情。