我正在尝试在Collection支持的Meteor原型中模拟一个延迟加载的项目数组,但具有反应性。
所以,说我有一本带有原型的书籍集合:
Book = function(document) {
this._title = document.title;
this._author = document.author;
// ...
};
Books.prototype = {
get id() {
// Read-only
return this._id;
},
get title() {
return this._title;
},
set title(value) {
this._title = value;
},
// ...
};
Books = new Meteor.Collections('books', {
transform: function(doc) {
return new Book(doc);
}
});
现在我想要一个货架的货架系列,但我想懒得装书:
Shelf = function(document) {
this._location = document.location;
this._floor = document.floor;
// ...
this._book_ids = document.book_ids;
};
Shelf.prototype = {
get id() {
// Read-only
return this._id;
},
get location() {
return this._location;
},
set location(value) {
this._location = location;
},
// ...
get book_ids() {
// This returns an array of just the book's _ids
return this._book_ids;
},
set book_ids(values) {
this._book_ids = values;
// Set _books to "undefined" so the next call gets lazy-loaded
this._books = undefined;
},
get books() {
if(!this._books) {
// This is what "lazy-loads" the books
this._books = Books.find({_id: {$in: this._book_ids}}).fetch();
}
return this._books;
}
};
Shelves = new Meteor.Collections('shelves', {
transform: function(doc) {
return new Shelf(doc);
}
});
所以,现在我有一个Self,我现在可以调用Shelf.books
并获取所有Books
,但在我调用之前它们不会被加载。此外,设置book_ids
的调用会导致数据无效,因此下一次调用books
会产生与该Books
相关联的新Shelf
。< / p>
现在,我如何让这种反应变为book_ids
的更新触发召回以找到正确的Books
,这样做会触发任何有Shelf.books
现在被触发刷新的人?或者,更好的是,如果更新Book
,那么与Book
(Shelf.books
和任何调用它的人)相关的所有内容也会被反应更新?