Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

meteor

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 pinterest like page with meteor.js).

On the server I am getting new Products from external API. I would like to publish the number of new items to all clients that they could update their local variables needed for layout to work well. How to do it?

It would be nice if I could publish/subscribe other kinds of data than Meteor.Collection. I found Meteor.deps, but what I understand it works only on client side.

like image 484
krzysu Avatar asked Nov 04 '22 04:11

krzysu


1 Answers

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);
like image 82
ram1 Avatar answered Nov 08 '22 05:11

ram1