Last Updated: February 25, 2016
·
791
· drgorb

publish data that is not in the database

I wanted to get some stats about my application and I used the facts package (more info here) which gives you a template to display some session data about your app.

As I wanted to find out how the package gets its info, I discovered that you can publish information which is not in the database. This can be really useful if you want to send some information to exactly one client.

it appears that the this object in the subscription has added, changed and removed methods that when called, update the client collection.

I wanted to try this out by creating an application that sends the server time to the client. The steps are small enough in number to list here

mrt create app
mrt add moment

once the application is created, update the file app.js

if (Meteor.isClient) {

   testCollection = new Meteor.Collection("testCollection");

   Template.hello.created = function () {
      this._stopHandle = Meteor.subscribe("test");
   }

   Template.hello.helpers(
      {
         greeting: function () {
            return "Welcome to app."
         },
         time: function(){
            return testCollection.findOne();
         }
      });

   Template.hello.events(
      {
         'click input': function () {
            // template data, if any, is available in 'this'
            if (typeof console !== 'undefined')
               console.log("You pressed the button");
         }
      });
}

if (Meteor.isServer) {
   var subs = {};

   Meteor.startup(function () {

   });

   Meteor.setInterval(function () {
      _(subs).each(function(sub, userId){
         sub.changed("testCollection", "server-time", {serverTime: moment().format("hh:mm:ss"), user: userId});
      })
   }, 1000);

   Meteor.publish("test", function () {
      if (this.userId){
         subs[this.userId] = this;
         this.added("testCollection", "server-time", {serverTime: moment().format("hh:mm:ss"), user: this.userId});
         this.ready();
      }
   })
}

in order to display the data in the HTML update the app.html

<head>
   <title>app</title>
</head>

<body>
{{> hello}}
</body>

<template name="hello">
   {{> loginButtons}}

   <h1>Hello World!</h1>
   {{greeting}} at {{time.serverTime}} for {{time.user}}
   <p>
      <input type="button" value="Click"/>
   </p>
</template>

and then just

mrt