在meteor中,pub/sub可以用于任意的内存中对象(不是mongo集合)

Dav*_*ave 5 javascript mongodb meteor

我想在我的流星应用程序中建立双向(双向)通信.但是我需要在不使用mongo集合的情况下完成它.

那么pub/sub可以用于任意的内存中对象吗?

是否有更好,更快或更低级别的方式?表现是我​​最关心的问题.

谢谢.

Geo*_*oth 5

是的,pub/sub可用于任意对象.Meteor的文档甚至提供了一个例子:

// 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.");
Run Code Online (Sandbox Code Playgroud)

在此示例中,counts-by-room是发布从返回的数据创建的任意对象Messages.find(),但您可以轻松地将源数据放在其他位置并以相同的方式发布它.你只需要提供相同addedremoved回调喜欢这里的例子.

您会注意到在客户端上有一个名为的集合counts,但这纯粹是在客户端内存中; 它没有保存在MongoDB中.我认为这是使用pub/sub的必要条件.

如果你想避免使用仅限内存的集合,你应该看一下Meteor.call.您可以创建一个Meteor.methodlike getCountsByRoom(roomId)并从客户端调用它Meteor.call('getCountsByRoom', 123),该方法将在服务器上执行并返回其响应.这更像是传统的Ajax做事方式,而你失去了Meteor的所有反应.