我可以只在meteor中发布Collections对象吗?

时间:2013-05-22 23:22:04

标签: collections meteor publish-subscribe

在DDP的介绍文章中,我读到任何内容都可以发布,但我已经在某处阅读过(例如在此Stackoverflow评论Publish arbitrary data and automatically update HTML中),只能发布集合。

那么事实在哪里?如果我们可以发布除收集之外的其他内容,我会看到一个例子,因为到目前为止找不到一个。

2 个答案:

答案 0 :(得分:1)

来自文档:http://docs.meteor.com/#meteor_publish

  

发布函数可以返回Collection.Cursor,在这种情况下,Meteor将发布该光标的文档。您还可以返回一组Collection.Cursors,在这种情况下,Meteor将发布所有游标。

所以目前你只能通过游标返回一个Collection(Collection.find()的结果)。

要返回您需要入侵sockjs流的其他数据(meteor用于与服务器通信的套接字库)。请注意,这并不能保证与未来版本的流星兼容。 Sockjs是用于流星在服务器(线路)之间进行通信的库

来自Publish arbitrary data and automatically update HTML *

客户端js

sc = new Meteor._Stream('/sockjs');   
sc.on('message', function(payload) {
    var msg = JSON.parse(payload);
    Session.set('a_random_message', JSON.stringify(msg.data));   
});

Template.hello.greeting = function () {
    return Session.get('a_random_message');   
}; 

服务器端js

ss = new Meteor._StreamServer();

ss.register(function (socket) {
    var data = {socket: socket.id, connected: new Date()}
    var msg = {msg: 'data', data: data};

     // Send message to all sockets (which will be set in the Session a_random_message of the client
     _.each(ss.all_sockets(), function(socket) {
         socket.send(JSON.stringify(msg));
     });   
}); 

答案 1 :(得分:1)

您也可以查看Meteor Streams。见下文。

  

假设您已经通过大气添加了流星流 - mrt add streams

sc = new Meteor.Stream('hello');

if(Meteor.isServer) {
  Meteor.setInterval(function() {
    sc.emit('a_random_message', 'Random Message: ' + Random.id());
  }, 2000);

  Meteor.permissions.read(function() { return true });
}

if(Meteor.isClient) {
  sc.on('a_random_message', function(message) {
    Session.set('a_random_message', message);
  });

  Template.hello.greeting = function () {
    return Session.get('a_random_message');   
  };
}