-
简单的订阅模式。这是您通常在简单的 Meteor 演示中看到的。
在客户端和服务器上,
Posts = new Meteor.Collection("posts");
仅在服务器上:
Meteor.publish("postsPub", function() {
return Posts.find()
});
仅在客户端上:
Meteor.subscribe("postsPub")
这将使用名为postsPub 的发布同步Posts 集合(在数据库中名为posts)。
-
一个出版物中的多个集合。您可以使用数组为单个发布发送多个光标。
在客户端和服务器上:
Posts = new Meteor.Collection("posts");
Comments = new Meteor.Collection("comments");
仅在服务器上:
Meteor.publish("postsAndComments", function() {
return [
Posts.find(),
Comments.find()
];
});
仅在客户端上:
Meteor.subscribe("postsAndComments");
这会使用名为 postsAndComments 的单个发布同步 Posts 集合和 Comments 集合。这种类型的发布非常适合关系数据;例如,您可能只想发布某些帖子以及仅与这些帖子关联的 cmets。请参阅 a package that can build these cursors automatically。
-
一个集合的多个出版物。您可以使用多个出版物为单个集合发送不同的数据切片,这些数据由 Meteor 自动合并。
在服务器和客户端上:
Posts = new Meteor.Collection("posts");
仅在服务器上:
Meteor.publish("top10Posts", function() {
return Posts.find({}, {
sort: {comments: -1},
limit: 10
});
});
Meteor.publish("newest10Posts", function() {
return Posts.find({}, {
sort: {timestamp: -1},
limit: 10
});
});
仅在客户端上:
Meteor.subscribe("top10Posts");
Meteor.subscribe("newest10Posts");
这会将站点上具有最多 cmets 的 10 个帖子以及 10 个最新帖子推送给用户,这会将两组数据合并到一个 Posts 集合中。如果最新帖子之一也是 cmets 最多的帖子,反之亦然,Posts 集合将包含少于 20 个项目。这是一个示例,说明 Meteor 中的数据模型如何让您在不自己实现细节的情况下进行强大的数据合并操作。
-
每个发布有多个订阅。您可以使用不同的参数从同一个发布中获取多组数据。
在服务器和客户端上:
Posts = new Meteor.Collection("posts");
仅在服务器上:
Meteor.publish("postsByUser", function(user) {
return Posts.find({
userId: user
});
});
仅在客户端上:
Meteor.subscribe("postsByUser", "fooUser");
Meteor.subscribe("postsByUser", "barUser");
这会导致fooUser 和barUser 的帖子都显示在posts 集合中。当您有几个不同的计算正在查看数据的不同切片并且可能会动态更新时,此模型很方便。请注意when you subscribe inside a Deps.autorun(...),Meteor 会自动在任何以前的同名订阅句柄上调用stop(),但如果您在autorun 之外使用这些订阅,您需要自己停止它们。截至目前,您不能在 autorun 计算中执行两个同名订阅,因为 Meteor 无法区分它们。
-
通过发布推送任意数据。您可以完全自定义发布,以在服务器和客户端上不需要相同的集合名称。事实上,服务器可以发布根本没有集合支持的数据。为此,您可以使用 API for the publish functions。
仅在服务器上:
Posts = new Meteor.Collection("posts");
Meteor.publish("newPostsPub", function() {
var sub = this;
var subHandle = null;
subHandle = Posts.find({}, {
sort: {timestamp: -1},
limit: 10
})
.observeChanges({
added: function(id, fields) {
sub.added("newposts", id, fields);
},
changed: function(id, fields) {
sub.changed("newposts", id, fields);
},
removed: function(id) {
sub.removed("newposts", id);
}
});
sub.ready();
sub.onStop(function() {
subHandle.stop();
})
});
仅在客户端上:
NewPosts = new Meteor.Collection("newposts");
Meteor.subscribe("newPostsPub");
这会使用名为newPostsPub。请注意,observeChanges 与 observe, which can do a bunch of other things 不同。
代码看起来很复杂,但是当您在发布函数中返回光标时,这基本上是 Meteor 在幕后生成的代码。以这种方式编写出版物可以让您更好地控制发送给客户的内容和不发送给客户的内容。不过要小心,因为您必须手动关闭observe 句柄并标记订阅何时准备就绪。有关详细信息,请参阅 Matt Debergalis' description of this process(但是,该帖子已过时)。当然,您可以将其与上面的其他部分结合起来,以获得非常细微和复杂的出版物。