gpt4 book ai didi

meteor - 如何将数据从服务器推送到所有不使用集合的客户端?

转载 作者:行者123 更新时间:2023-12-04 21:19:44 24 4
gpt4 key购买 nike

我需要通知客户有关服务器端的变化。在我的情况下,我在服务器和客户端上使用不同的集合(在这个问题中更多关于它: how would you build pinterest like page with meteor.js )。

在服务器上,我从外部 API 获取新产品。我想向所有客户发布新项目的数量,他们可以更新布局正常工作所需的局部变量。
怎么做?

如果我可以发布/订阅除 Meteor.Collection 之外的其他类型的数据,那就太好了。我找到了 Meteor.deps,但据我所知,它只适用于客户端。

最佳答案

为了完成你想要的,你需要另一个集合——在客户端上。在服务器上,在发布功能中,从头开始构建文档,将产品的当前计数分配给属性。使用observe()和set,修改count在产品中添加或删除文档时。订阅 count客户端上的“记录集”。

// Server
Meteor.publish('count', function () {
// Build a document from scratch
var self = this;
var uuid = Meteor.uuid();
var count = Products.find().count();
// Assign initial Products count to document attribute
self.set('count', uuid, {count: count});

// Observe Products for additions and removals
var handle = Products.find().observe({
added: function (doc, idx) {
count++;
self.set('counts', uuid, {count: count});
self.flush();
},
removed: function (doc, idx) {
count--;
self.set('counts', uuid, {count: count});
self.flush();
}
});
self.complete();
self.flush();
self.onStop(function () {
handle.stop();
});
});

// Client
Counts = new Meteor.Collection('count');
Meteor.subscribe('count');
console.log('Count: ' + Counts.findOne().count);

关于meteor - 如何将数据从服务器推送到所有不使用集合的客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14814118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com