简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM