Day three: Schat

September 28, 2015

Schat is a chat application to get in touch with other like minded individuals. Build on the power of Meteor and designed with some material goodness.

live demo

On this third day I wanted to create a full blown chat app. I build it with Meteor because of the need for fast prototyping and realtime out of the box. If you have not heard of Meteor before. Read my introductionary article here.

The biggest challenge I faced was getting the chatbox to scroll down whenever a new message appeared. In theory it sounds simple enough but there are some factors which make it a bit tricky.

The first obstacle was to know when a new message got added. All right, easy. Using observe on a reactive query should get the job done! First obstacle gone. Bring on the next!

The second obstacle was scrolling down the chat box. I already know when a new message is added. However, at the initial page load. The added event will be triggered for every single message in the entire collection. This is of course not what we want. To only scroll down to the last message I decided to enforce scrolling only after all the old messages have been loaded.

I ended up going with this:

Template.chatBox.onRendered(function () {
  this.autorun(() => {
    let messages = this.messages.get();
    let now = moment();
    messages.observe({
      added: (doc) => {
        if (moment(doc.creationDate).isAfter(now)) {
          $('.chat').scrollTop($('.chat')[0].scrollHeight);
        }
      }
    });
  });
});

PS: ES2015 is awesome!

Meteor 1.2 supports Ecmascript2015 which makes it an even more fun platform to build applications with! Checkout what a ES2015 Meteor app looks like here and don’t forget to leave a star on the repo.

Comments