Meteor Capture

Incoming

If you've ever been on twitter, you have no doubt seen this prompt that notifies you when there's new tweets.

Let's look at how easily we can do this with Meteor.

Client stuff

Templates

<head>  
  <title>incoming</title>
</head>

<body>  
  {{> feed}}
</body>

<template name="feed">  
  {{#if incoming.count}}
    <p>{{incoming.count}} new! <a class="new">Show</a></p>
  {{/if}}

  <ul>
    {{#each feed}}
      {{> feedItem}}
    {{/each}}
  </ul>
</template>

<template name="feedItem">  
  <li><strong>{{name}}</strong>: {{message}}</li>
</template>  

Javascript

if (Meteor.isClient) {  
  Meteor.subscribe('feed');

  Template.feed.created = function() {
    Session.set('feedPopulatedAt', new Date());
  };

  Template.feed.helpers({
    incoming: function() {
      return Feed.find({ createdAt: { $gt: Session.get('feedPopulatedAt') }}, { sort: { createdAt: -1 }});
    },
    feed: function() {
      return Feed.find({ createdAt: { $lte: Session.get('feedPopulatedAt') }}, { sort: { createdAt: -1 }});
    }
  });

  Template.feed.events({
    'click .new': function() {
      Session.set('feedPopulatedAt', new Date());
    }
  });
}

Both

(server and client)

Feed = new Meteor.Collection('feed');

// This is a package I wrote for test data
// http://atmospherejs.com/package/factory
Factory.define('feed', Feed, {  
  createdAt: function() { return new Date(); },
  name: function() { return Fake.user().fullname; },
  message: function() { return Fake.sentence(); }
});

Just the server

if (Meteor.isServer) {  
  // Simulates new data
  Meteor.setInterval(function() {
    Factory.create('feed');
  }, 3000);

  Meteor.startup(function() {
    Meteor.publish('feed', function() {
      return Feed.find({}, { sort: { createdAt: -1 }});
    });
  });
}

Try the demo app
https://github.com/dburles/meteor-capture-incoming

Have fun! If you have any questions, please leave them below.

comments powered by Disqus