假设我有模特:
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
});
在复杂的业务逻辑中,我需要Books的基本商店对象:
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 :(得分: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);
});