如何在模板之间隔离订阅数据?
例如,我有一个带有两个不同模板的页面:
1)主题清单
2)热门话题。
为此,我有两个不同的、不同的、Meteor.publish和Subscribtions。
1)在主题列表模板中,我按CreatedAt-字段进行了排序。
Meteor.subscribe('topics');
Template.topics_main.helpers({
topics:function(){
return Topic.find({},{sort: {createdAt: -1}});
}
});2)在流行列表中,我按等级字段对数据进行排序。
Meteor.subscribe('popularTopics');
Template.top_topics.helpers({
topics:function(){
return Topic.find({}, {
sort: {
views: -1
},
limit: 5
});
}
});当我滚动我的主题列表时,我将从流行话题中获得数据。这不太好:)如何使用不同的订阅来隔离数据bweetwen的两个模板,而只能分离一种类型的集合?
发布于 2016-08-16 13:16:31
observeChanges可能是你所需要的。它允许您将文档发布到特定的集合中,这样您就可以让两个发布(topics和popularTopics)从服务器上的同一个集合(Topics)中获取数据,但将其发送到客户端上的不同集合(例如Topics和PopularTopics)。
下面是一个例子:
// globally somewhere
const Topics = new Mongo.Collection('topics');
const PopularTopics = new Mongo.Collection('populartopics');添加发布,observeChanges将已发布的文档发送到客户端上的两个不同集合:
// topics.publications.js
const abstractPublish = function (collectionName, query) {
const cursor = Topics.find(query);
const cursorHandle = cursor.observeChanges({
added(id, fields) {
this.added(collectionName, id, fields);
},
changed(id, fields) {
this.changed(collectionName, id, fields);
},
removed(id) {
this.removed(collectionName, id);
}
});
this.onStop(()=>{
if (cursorHandle) cursorHandle.stop();
});
this.ready();
};
Meteor.publish('topics', function () {
// set up a publication to the "topics" collection
abstractPublish.call(this, 'topics', {});
});
Meteor.publish('popularTopics', function () {
// set up a publication to the "populartopics" collection
abstractPublish.call(this, 'populartopics', {popular: true});
});然后设置模板级订阅:
// topics_main.js
Template.topics_main.onCreated(function () {
this.autorun(() => {
this.subscribe('topics', function () {
Topics.find().fetch(); // returns all topics
);
});
});在你的热门话题模板中:
// top_topics.js
Template.top_topics.onCreated(function () {
this.autorun(() => {
this.subscribe('popularTopics', function () {
PopularTopics.find().fetch(); // returns only topics that have {popular: true}
);
});
});发布于 2016-08-16 09:09:03
这是“流星”目前出版模式的一个已知限制。
为了克服这一问题,人们想到了一些选择:
阿波罗堆可能也很方便。
https://stackoverflow.com/questions/38970398
复制相似问题