javascriptbackbone.jsbackbone-eventsbackbone.js-collections

Backbone listen to change event on collection of collection


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
})

Solution

  • Yes.. but to each one:

    this.get('books').forEach(function(book) {
        book.get('authors').on('change', this.onChage)
    });