Meteor Observe Changes - Detect Changes Client side


#1

So,one of the things I like about NodeJS and Websockets is that i can set certain things to happen when messages / certain triggers are sent back and forth (blink the cursor, or change the background color of the div for the new info, etc.

I’m trying to use observeChanges from the Meteor API, but I’m definitely having issues (what’s new with me, right?)

On my client I have

import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { MyCollection } from '../imports/api/myCollection.js';

Template.showChanges.onCreated(function changesOnCreated() {
    Meteor.subscribe('myCollection');
});

import './main.html';

Template.showChanges.helpers({
    messages() {
        return MyCollection.find({});
    },
    test: function () {
        var count = 0;
        var query = MyCollection.find({});
        query.observeChanges({
          added: function (id, message) {
            count++;
            console.log(myCollection.message + " brings the total to " + count + " messages.");
            document.write("Message Added. Count is: " + count);
          },
          changed: function (id, message) {
            count++;
            console.log(MyCollection.message + " was changed.");
            document.write("Message changed. Count increased: " + count);
          },
          removed: function () {
            count--;
            console.log("Lost one. We're now down to " + count + " admins.");
            document.write("Message removed. Count decreased: " + count);
          }
        });
    },
});

My first helper works fine, but I get nothing from the second ‘test’ helper with the observe changes in it. If you have suggestions, or a better way to detect changes to data, and make updates to DOM, let me know.


#2

YMMV but here is how I handle it in one instance:

Template.uploads.onCreated(function () {
  let query = Uploads.find();
  let handle = query.observeChanges({
    changed: function (id, fields) {
      // changed stuff
    },
    added: function (id, fields) {
      // added stuff
     }
  });
});

I’m thinking moving it from a helper to an onCreated will get you where you want to be?


#3

for events, as opposed to state, consider an emitter. rocketchat:streamer seems the current choice for this.


#4

Thanks to both of you, I’ll see what I can work out on it.

I’ve seen the streamer before. A couple of libraries actually, but was really new to Meteor, so didn’t even think about them this time.

I’ll check onCreated first, then make another test project to try some streamers.


#5

also see this great blog on this particular meteor API that you are looking at. it draws out the Nexus between .observe and DDP.