1

Is it possible to listen to add, remove, reset, change event of one collection which is part of another collection?

For example: Library having a collection of books. And each book can have multiple authors. Is there a way I can listen to event on authors in Library model?

Library.js

var Library = Backbone.Model.extend({
    initialize: function() {
        this.get('books').on('change:authors', this.onChange);
    }
}

Books.js

var Book = Backbone.Model.extend({
})
var Books = Backbone.Collection.extend({
    Model: Book
})

Authors.js

var Author = Backbone.Model.extend({
})
var Authors = Backbone.Collection.extend({
    Model: Author
})
Hemanth S R
  • 1,115
  • 2
  • 16
  • 27
  • Please clarify some questions. Why should the library listen to author changes (what will it do with these events)? Will your server deliver the whole data structure of array of books with array of authors (one endpoint) or do you alter each book with the author data? Do you need to write changes back to the server (are authors creatable/editable)? How do you define authors on each book if you alter the books (1st question)? – try-catch-finally Jul 01 '17 at 14:56
  • 1
    You really should rethink listening nested collections like that, it's really inefficient and rigid on the long run. I would even avoid putting the collection in the attributes. There are [different ways to nest a collection in a model](https://stackoverflow.com/a/40823148/1218980), choose wisely. – Emile Bergeron Jul 04 '17 at 14:10

1 Answers1

1

Yes.. but to each one:

this.get('books').forEach(function(book) {
    book.get('authors').on('change', this.onChage)
});
AlexisCaffa
  • 339
  • 3
  • 13