Search code examples
backbone.jssynchronization

Synchronization for nested collections


Suppose I have models:

var Book = Backbone.Model.extend({
  // ... 
});

var Store = Backbone.Model.extend({
  getBooks: function(){
    this.books = new Books(App.Singletons.AllBooks.where({storeId: this.id}));
    return this.books;
  }
});

Store has many books.

Also suppose I have a collection:

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

In a complex business logic I need a base store object for the Books:

var App = App || {};
App.Singletons = App.Singletons || {};
var books = new Books();
books.fetch();
App.Singletons.AllBooks = books;
// ...

What the best way for syncing a singleton model for operations like this:

var store = new Store({id: 1});
store.fetch();
store.getBooks();

store.books.add(...);
store.books.remove(...);
// etc
// There I need to sync with App.Singletons.AllBooks

Now I'm overriding these methods in the Books collections. And there the App.Singletons.AllBooks is being synced. I think there should be another better solution for this task. Thanks for helping.


Solution

  • If you want to keep something in "sync", override the sync method.

    In the case of store:

    var Store = Backbone.Model.extend({
      getBooks: function() {
        this.books = new Books(App.Singletons.AllBooks.where({
          storeId: this.id
        }));
        return this.books;
      },
      sync: function(method, model, options) {
        switch (method) {
          case 'create':
            //your logic to sync with App.Singletons.AllBooks
            break;
          case 'read':
            //your logic to sync with App.Singletons.AllBooks
            break;
          case 'update':
            //your logic to sync with App.Singletons.AllBooks
            break;
          case 'delete':
            //your logic to sync with App.Singletons.AllBooks
            break;
        }
      }
      Backbone.prototype.sync.call(this, method, method, options);
    });