我想在我的 meteor 应用程序中建立双向(双向)通信。但我需要在不使用 mongo 集合的情况下做到这一点。
那么 pub/sub 可以用于任意内存对象吗?
有没有更好、更快或更低级别的方法?性能是我最关心的问题。
谢谢。
最佳答案
是的,pub/sub 可以用于任意对象。 Meteor’s docs even provide an example :
// server: publish the current size of a collection
Meteor.publish("counts-by-room", function (roomId) {
var self = this;
check(roomId, String);
var count = 0;
var initializing = true;
// observeChanges only returns after the initial `added` callbacks
// have run. Until then, we don't want to send a lot of
// `self.changed()` messages - hence tracking the
// `initializing` state.
var handle = Messages.find({roomId: roomId}).observeChanges({
added: function (id) {
count++;
if (!initializing)
self.changed("counts", roomId, {count: count});
},
removed: function (id) {
count--;
self.changed("counts", roomId, {count: count});
}
// don't care about changed
});
// Instead, we'll send one `self.added()` message right after
// observeChanges has returned, and mark the subscription as
// ready.
initializing = false;
self.added("counts", roomId, {count: count});
self.ready();
// Stop observing the cursor when client unsubs.
// Stopping a subscription automatically takes
// care of sending the client any removed messages.
self.onStop(function () {
handle.stop();
});
});
// client: declare collection to hold count object
Counts = new Mongo.Collection("counts");
// client: subscribe to the count for the current room
Tracker.autorun(function () {
Meteor.subscribe("counts-by-room", Session.get("roomId"));
});
// client: use the new collection
console.log("Current room has " +
Counts.findOne(Session.get("roomId")).count +
" messages.");
在本例中,counts-by-room
发布了一个任意对象,该对象由 Messages.find()
返回的数据创建,但您也可以轻松获取您的在其他地方获取数据并以相同的方式发布。您只需要提供与此处示例相同的 added
和 removed
回调。
您会注意到在客户端有一个名为 counts
的集合,但这纯粹是在客户端的内存中;它没有保存在 MongoDB 中。我认为这是使用 pub/sub 的必要条件。
如果您甚至想避免仅在内存中收集,您应该查看 Meteor.call
。您可以创建一个 Meteor.method
像 getCountsByRoom(roomId)
并从客户端调用它像 Meteor.call('getCountsByRoom', 123)
该方法将在服务器上执行并返回其响应。这更像是传统的 Ajax 做事方式,并且您失去了 Meteor 的所有反应性。
关于javascript - 在 meteor 中,发布/订阅可以用于任意内存对象(不是 mongo 集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455914/