How to push data from server to all clients not using Collections?

前端 未结 2 2044
盖世英雄少女心
盖世英雄少女心 2021-02-10 01:07

I need to inform clients about changes on server side. In my case I am using different Collections on server and on client (more about it in this question: how would you build p

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-10 01:52

    To accomplish what you want you do need another collection - on the client. On the server, in a publish function, build a document from scratch assigning the current count of Products to an attribute. Using observe() and set, modify count when documents are added or removed from Products. Subscribe to the count "record set" on the client.

    // 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);
    

提交回复
热议问题