1

我正在尝试在集合支持的 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);
  }
});

现在我想要一个 Shelves 集合,但我想延迟加载书籍:

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,但直到我调用它才加载它们。此外,对 set 的调用book_ids将导致数据无效,因此下一次调用将books产生Books与 that 关联的新集合Shelf

现在我该如何做出这种反应,以便更新book_ids触发召回以找到正确的Books,并且这样做会触发Shelf.books现在将触发刷新的任何人?或者,更好的是,如果 aBook被更新,那么与它相关的所有内容BookShelf.books以及调用它的任何人)也会被响应更新?

4

0 回答 0