在支持Collection的原型中是否存在延迟加载的getter模式(在JavaScript / Meteor中构建反应式ORM关系)

时间:2015-01-20 12:50:53

标签: javascript meteor meteor-collections

我正在尝试在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,那么与BookShelf.books和任何调用它的人)相关的所有内容也会被反应更新?

0 个答案:

没有答案