【问题标题】:Can I publish only Collections object in meteor?我可以在流星中只发布 Collections 对象吗?
【发布时间】:2013-05-18 04:14:18
【问题描述】:

在 DDP 的介绍文章中,我读到任何东西都可以发布,但我在某个地方(例如在此 Stackoverflow 评论 Publish arbitrary data and automatically update HTML 中)读到只能发布集合。

那么真相在哪里?如果我们可以发布集合以外的其他内容,我会想看一个示例,因为我目前找不到。

【问题讨论】:

    标签: collections meteor publish-subscribe


    【解决方案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));
         });   
    }); 
    

    【讨论】:

    • 谢谢。可以说另一个技巧是为我想要发布的任何变量/对象创建一个集合吗?
    【解决方案2】:

    您也可以查看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');   
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 2018-08-09
      • 1970-01-01
      • 2012-06-07
      • 2014-12-14
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多