Meteor Capture

Publishing anything

While it may not be all that obvious, data that we publish doesn't only have to come from Mongo. In fact, we can publish anything we like and that can be quite useful.

Client

Let's take a look at our client side code. This should all look pretty familier but with one key difference. We've defined our books collection client side only.

if (Meteor.isClient) {  
  // Client side Collection
  Books = new Mongo.Collection('books');

  Meteor.subscribe('books');

  Template.body.helpers({
    books: function() {
      return Books.find();
    }
  });
}

The reason why we're doing this is that we don't want to store any data on the server, we simply want a place on the client where we can store data we receive from our publication.

Server

Over on the server, we've created a publication named books.

if (Meteor.isServer) {  
  Meteor.publish('books', function() {
    var self = this;

    // Some very interesting books
    var books = [
      { title: 'Book 1' },
      { title: 'Book 2' },
      { title: 'Book 3' }
    ];

    _.each(books, function(book) {
      self.added('books', Random.id(), book);
    });

    self.ready();
  });
}

The key thing here is the use of the added and ready methods. added informs the subscriber that a document has been added. And ready informs the subscriber that all of our data has been initially sent.

Let's go over the arguments that we're passing to the added method.

self.added('books', Random.id(), book);

The first argument is the name of the collection on the client we wish to populate, the second argument is the _id of the document (in this case we're using Random.id() see more on that here), and finally the document we wish to add.

Along with added we also have changed and removed. Check out the full documentation here: http://docs.meteor.com/#meteor_publish


What's neat about all this is that data we publish can come from anywhere, for example a third party API. Perhaps that's for a separate post, if anyone's interested :)

Take a look at the follow up article! Publishing data from an external API

Example app

https://github.com/dburles/meteor-capture-pubsub
Check out the example application on GitHub.

http://meteorpad.com/pad/XY5SF7EGStxuZpHXn
Play around with the live app running on MeteorPad!

comments powered by Disqus