发布和订阅

Meteor 服务端可以通过Meteor.publish发布文档集,同时客户端可以通过Meteor.subscribe订阅这些发布。 任何客户端订阅的文档都可以通过find方法进行查询使用。

默认情况下,每个新创建的 Meteor 应用包含有 autopublish 包,它会自动为每个客户端发布所有可用的文档。 为了可以更细化的控制不同客户端所接收的数据文档,首先应该在终端移除 autopublish:

$ meteor remove autopublish

现在,你可以使用Meteor.publishMeteor.subscribe 来控制不同的文档从服务端推送到不同的客户端了。

Meteor.publish(name, func)

Server

Publish a record set.

Arguments

name String

Name of the record set. If null, the set has no name, and the record set is automatically sent to all connected clients.

func Function

Function called on the server each time a client subscribes. Inside the function, this is the publish handler object, described below. If the client passed arguments to subscribe, the function is called with the same arguments.

将数据发布到客户端,通过在服务端调用 Meteor.publish,需要传入两个参数:该记录集的名称,以及一个会在每一次客户端订阅该记录集的时候被调用的发布功能函数。

发布功能通过返回在一些collection调用collection.find(query)的结果。通过query来限制发布的文档集:

// 发布已登录用户的文章集合
Meteor.publish("posts", function () {
  return Posts.find({ createdBy: this.userId });
});

你可以发布来自多个collection的文档,通过返回一个collection.find 结果集合:

// 发布一个单独的文章和对应的评论
Meteor.publish("postAndComments", function (postId) {
  // 检查参数
  check(postId, String);

  return [
    Posts.find({ _id: postId }),
    Comments.find({ postId: roomId })
  ];
});

在发布功能里,this.userId是当前登录用户的_id, 在某些文档仅对特定用户可见时,可以用其来过滤集合。 如果客户端登录的用户发生改变,发布功能也将自动使用新的userId,所以新用户无法访问任何只限于之前登录用户的文档。

Meteor.subscribe(name, [arg1, arg2...], [callbacks])

Client

Subscribe to a record set. Returns a handle that provides stop() and ready() methods.

Arguments

name String

Name of the subscription. Matches the name of the server's publish() call.

arg1, arg2... Any

Optional arguments passed to publisher function on server.

callbacks Function or Object

Optional. May include onStop and onReady callbacks. If there is an error, it is passed as an argument to onStop. If a function is passed instead of an object, it is interpreted as an onReady callback.

客户端调用 Meteor.subscribe来订阅服务端发布的文档集合。 客户端可以进一步过滤文档集合通过调用collection.find(query). 当任何通过发布功能发布的可访问的数据在服务端发生改变时,发布功能会自动返回和更新发布的文档集合推送给客户端。

onReady回调函数在服务端已经发送了订阅的所有初始化数据时被调用,无需传入任何参数。 onStop订阅不管以任何原因被终止时调用 ;如果订阅失败是由于服务端错误,它将收到一个Meteor.Error

Meteor.subscribe 返回一个订阅句柄,是一个包含以下方法的对象:

stop()

取消订阅。这通常会导致服务器引导客户端从客户端缓存中删除订阅的数据。

ready()

如果服务端已经设置状态为ready,将会返回 True。一个反应式数据源。

如果你在Tracker.autorun里调用Meteor.subscribe, 当运算返回时,订阅将被自动取消(所以如果合适的话,一个新的订阅会被创建), 意味着你不能够在来自Tracker.autorun里的订阅中调用stop