Set object on iteration
In the parent view, I pass in a portion of the underlying model (the model is named Library, so I pass the object Library.book
as this.book
. When I alert this.book
, it looks something like this:
{"favoritePages":["384","383","385"],"summariesOfFavoritePages":["Cool","Great","Informative"]}
I have a basic view that looks like this:
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 SET
});
}
});
The part of the library view (parent view) that the model goes through looks like this:
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();
});
},
Basically, I want to update this.book
with this.model.set
, but not sure how to do this with an array inside the books iteration?
source to share
I can think of a couple of solutions:
- Same as @Lochemage suggested. Use bookIndex, but guess the book index will not change. To install the model, I would suggest the following:
if (this.model.get ('library'). books [this.bookIndex]! = undefined)
this.model.get ('library'). books [this.bookIndex] = this.book;
- Use Underscore findWhere library . The guess
book
is unique across all attributeslibrary.books
.
var book = _.findWhere(this.model.get("library").books, this.book);
if(book != undefined)
book = this.book;
source to share
You can also remember the index of the book inside your library bookstore.
_.each(this.model.get("library").books, function(book, bookIndex){
var libraryBookView = new LibraryBookView({
el: $('.content'),
book: book,
bookIndex: bookIndex,
model: this.model
});
libraryBookView.render();
});
Then in the book library class where you want to set the model:
this.model.set('library.books[' + this.bookIndex + ']', this.book);
This assumes your book index will not change ... if they do, you will either have to update the index on each view of the book or do something else.
source to share