Meteor docs中的messages-count示例如何工作? [英] How does the messages-count example in Meteor docs work?

查看:95
本文介绍了Meteor docs中的messages-count示例如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法完全理解文档中的这个示例...我试过运行它一堆不同的方式,所以我可以观察它是如何工作的等等。

Having trouble full understanding this example from the docs... I tried running it a bunch of different ways so I could observe how it works, etc.

你如何订阅这个?我们可以包含使这项工作所需的客户端代码吗?

How do you subscribe to this? Can we include the client side code needed to make this work?

是否有一个名为 messages-count 的集合? 房间是一组消息吗?我们可以在示例中包含集合定义吗?

Is there a collection called messages-count? Is a Room a collection of messages? Can we include the collection definitions in the example?

任何关于此的提示都会很棒!

Any tips on this would be great!

注意:这是最初发布此问题时出现的代码(2012年5月)。它现在更简单。

NOTE: this is the code as it appeared when this question was initially posted (May 2012). It's simpler now.

// server: publish the current size of a collection
Meteor.publish("messages-count", function (roomId) {
  var self = this;
  var uuid = Meteor.uuid();
  var count = 0;

  handle = Room.find({room_id: roomId}).observe({
    added: function (doc, idx) {
      count++;
      self.set("messages-count", uuid, "count", count);
      self.flush();
    },
    removed: function (doc, idx) {
      count--;
      self.set("messages-count", uuid, "count", count);
      self.flush();
    }
    // don't care about moved or changed
  });

  // remove data and turn off observe when client unsubs
  self.onStop(function () {
    handle.stop();
    self.unset("messages-count", uuid, "count");
    self.flush();
  });
});


推荐答案

感谢您提示我写一个更清晰的解释。这是我的评论的更全面的例子。我清理了一些错误和不一致的地方。下一个docs release将使用它。

Thanks for prompting me to write a clearer explanation. Here's a fuller example with my comments. There were a few bugs and inconsistencies that I've cleaned up. Next docs release will use this.

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

Meteor.publish is quite flexible. It's not limited to publishing existing MongoDB collections to the client: we can publish anything we want. Specifically, Meteor.publish defines a set of documents that a client can subscribe to. Each document belongs to some collection name (a string), has a unique _id field, and then has some set of JSON attributes. As the documents in the set change, the server will send the changes down to each subscribed client, keeping the client up to date.

我们将在此处定义一个文档集,名为按房间计算,其中包含名为的集合中的单个文档计数。该文档将包含两个字段: roomId ,其中包含房间ID, count :消息总数在那个房间里。没有名为的真正MongoDB集合计数。这只是我们的Meteor服务器将发送到客户端的集合的名称,并存储在名为客户端集合中

We're going to define a document set here, called "counts-by-room", that contains a single document in a collection named "counts". The document will have two fields: a roomId with the ID of a room, and count: the total number of messages in that room. There is no real MongoDB collection named counts. This is just the name of the collection that our Meteor server will be sending down to the client, and storing in a client-side collection named counts.

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

To do this, our publish function takes a roomId parameter that will come from the client, and observes a query of all Messages (defined elsewhere) in that room. We can use the more efficient observeChanges form of observing a query here since we won't need the full document, just the knowledge that a new one was added or removed. Anytime a new message is added with the roomId we're interested in, our callback increments the internal count, and then publishes a new document to the client with that updated total. And when a message is removed, it decrements the count and sends the client the update.

当我们第一次调用 observeChanges ,对于已存在的每条消息,将立即运行一些添加的回调。然后,每当添加或删除消息时,将触发未来的更改。

When we first call observeChanges, some number of added callbacks will run right away, for each message that already exists. Then future changes will fire whenever messages are added or removed.

我们的发布函数还注册了一个 onStop 处理程序来清理当客户端取消订阅时(手动或断开连接)。此处理程序从客户端删除属性并删除正在运行的 observeChanges

Our publish function also registers an onStop handler to clean up when the client unsubscribes (either manually, or on disconnect). This handler removes the attributes from the client and tears down the running observeChanges.

每次运行时都会运行一个发布函数新客户订阅按房间计算,因此每个客户端将代表其运行 observeChanges

A publish function runs each time a new client subscribes to "counts-by-room", so each client will have an observeChanges running on its behalf.

// 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 构造函数。

Now, on the client, we can treat this just like a typical Meteor subscription. First, we need a Mongo.Collection that will hold our calculated counts document. Since the server is publishing into a collection named "counts", we pass "counts" as the argument to the Mongo.Collection constructor.

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

然后我们可以订阅。 (您可以在声明收集之前实际订阅:Meteor将对传入的更新进行排队,直到有位置放置它们。)订阅的名称按房间计算,它需要一个参数:当前房间的ID。我把它包装在 Deps.autorun 中,以便当 Session.get('roomId')更改时,客户端将自动取消订阅旧房间的计数并重新订阅新房间的数量。

Then we can subscribe. (You can actually subscribe before declaring the collection: Meteor will queue the incoming updates until there's a place to put them.) The name of the subscription is "counts-by-room", and it takes one argument: the current room's ID. I've wrapped this inside Deps.autorun so that as Session.get('roomId') changes, the client will automatically unsubscribe from the old room's count and resubscribe to the new room's count.

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

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

Finally, we've got the document in Counts and we can use it just like any other Mongo collection on the client. Any template that references this data will automatically redraw whenever the server sends a new count.

// client: use the new collection
console.log("Current room has " + Counts.findOne().count + " messages.");

这篇关于Meteor docs中的messages-count示例如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆