2015-12-25 210 views
0

假設我有型號:同步嵌套集合

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

商店has many書籍。

而且假設我有一個集合:

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

在複雜的業務邏輯,我需要的書籍基本存儲對象:

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

什麼爲同步單身模型的最佳途徑這樣的操作:

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 

現在我重寫這些方法在Books集合。那裏App.Singletons.AllBooks正在同步。 我認爲應該有另一個更好的解決方案來完成這項任務。 感謝您的幫助。

回答

0

如果您想保留某些內容爲「同步」,請覆蓋同步方法。

在店內的情況:

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