aurath
aurath

Reputation: 1407

Simple chat program in Meteor. How do I hook up a callback to fire when new messages come in?

I'm working on this simple chat app to learn Meteor and I'm a little stuck here. I have a nicely working chatroom, but I'm having trouble hooking up a function to fire when a chat comes in from another person. I'd like to automatically scroll to the bottom of the window and update the favicon notification when this happens. I have a template chatWindow that looks like this:

<template name="chatWindow">
    <div class="textWindow">
        {{#each messages}}
            <span class="username {{#if me}}me{{/if}}">{{username}}</span><span class="message">{{message}}</span>
            <br />
        {{/each}}
    </div>
    <br />
    <form>
        {{#if currentUser}}
            <input type="text" name="chatTextBox" id="chatTextBox" />
        {{/if}}
    </form>
</template>

The {{#each messages}} block works great for grabbing the updated collection of chat messages automatically, but how do I fire an event when it's updated? I've tried Template.chatWindow.onRender() and Template.chatWindow.rendered but they both only fire the first time.

Upvotes: 0

Views: 63

Answers (1)

Michael Paddock
Michael Paddock

Reputation: 260

Observe is usually the way to go here. Assuming messages are stored in a collection Messages, you can do something like:

Messages.find().observe({
  added: function (document) {
    // Set some Session vars or do some jquery or update other collections
  }
});

Observe works on both the client and server, and can also register callbacks for document changed events and document removed events.

Upvotes: 1

Related Questions