您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Meteor文档中的messages-count示例如何工作?

Meteor文档中的messages-count示例如何工作?

感谢您提示我写一个更清晰的解释。这是带有我的评论的完整示例。我已经清理了一些错误和不一致之处。下一个文档版本将使用此功能

Meteor.publish非常灵活。它不仅限于将现有的MongoDB集合发布到客户端:我们可以发布任何我们想要的东西。具体来说,Meteor.publish定义客户可以订阅的一组文档 。每个文档都属于某个集合名称一个字符串),具有一个唯一的_id字段,然后具有一组JSON属性。当集合中的文档发生更改时,服务器会将更改向下发送给每个订阅的客户端,以使客户端保持最新状态。

我们将在此处定义一个名为的文档集,该文档集"counts-by-room"包含一个名为的集合中的单个文档"counts"。该文档将具有两个字段:一个roomId具有房间ID的字段,以及count:该房间中消息的总数。没有名为的实际MongoDB集合counts。这只是Meteor服务器将向下发送给客户_端的_ 集合的名称,并存储在名为的 客户端 集合中counts

为此,我们的publish函数采用一个roomId来自客户端的参数,并观察对该房间中所有Messages(在其他位置定义)的查询。我们可以在observeChanges这里使用更高效的观察查询形式,因为我们不需要完整的文档,而只是知道添加删除一个新文档。每当添加新消息并添加roomId我们感兴趣的消息时,我们的回调都会增加内部计数,然后将具有更新后总数的新文档发布到客户端。当删除一条消息时,它将减少计数并向客户端发送更新。

首次调用observeChangesadded对于每个已存在的消息,将立即运行一些回调。然后,无论何时添加删除邮件,将来的更改都会触发。

我们的发布功能注册一个onStop处理程序,以在客户端退订(手动或断开连接)时进行清理。该处理程序从客户端删除属性,并取消运行observeChanges

每次新客户端订阅"counts-by-room",都会运行publish函数,因此每个客户端都将observeChanges代表其运行。

// server: publish the current size of a collection
Meteor.publish("counts-by-room", function (roomId) {
  var self = this;
  var count = 0;
  var initializing = true;

  var handle = Messages.find({room_id: roomId}).observeChanges({
    added: function (doc, idx) {
      count++;
      if (!initializing)
        self.changed("counts", roomId, {count: count});  // "counts" is the published collection name
    },
    removed: function (doc, idx) {
      count--;
      self.changed("counts", roomId, {count: count});  // same published collection, "counts"
    }
    // don't care about moved or changed
  });

  initializing = false;

  // publish the initial count. `observeChanges` guaranteed not to return
  // until the initial set of `added` callbacks have run, so the `count`
  // variable is up to date.
  self.added("counts", roomId, {count: count});

  // and signal that the initial document set is Now available on the client
  self.ready();

  // turn off observe when client unsubscribes
  self.onStop(function () {
    handle.stop();
  });
});

现在,在客户端上,我们可以将其视为典型的Meteor订阅。首先,我们需要一个Mongo.Collection可以保存我们计算的计数文档的文件。由于服务器正在发布到名为的集合中"counts",我们将其"counts"作为参数传递给Mongo.Collection构造函数

// client: declare collection to hold count object
Counts = new Mongo.Collection("counts");

然后我们可以订阅。(实际上,您可以在声明集合之前进行订阅:Meteor会将传入的更新排队,直到有放置它们的位置为止。) 订阅名称"counts-by-room",它带有一个参数:当前房间的ID。我将其包装在内部,Deps.autorun以便进行Session.get('roomId')更改时,客户端将自动取消订阅旧房间的计数,然后重新订阅新房间的计数。

// client: autosubscribe to the count for the current room
Tracker.autorun(function () {
  Meteor.subscribe("counts-by-room", Session.get("roomId"));
});

最后,我们已经获得了文档,Counts并且可以像客户端上的任何其他Mongo集合一样使用它。每当服务器发送新计数时,任何引用此数据的模板都将自动重绘。

// client: use the new collection
console.log("Current room has " + Counts.findOne().count + " messages.");
其他 2022/1/1 18:17:33 有515人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶