How to trigger a Client JS method when a subscribed data is changed

I want my app to fire a method (client side) when a particular subscribed data is changed? for example, the client side has this following subscription
Meteor.subscribe('thePlayers');
thePlayers subscription returns a collection of data which is being displayed in the html through the template.

so whenever the collection get changed, Meteor automatically change the data in the HTML also. Besides this feature, I want my app to fire a method say fire() to be executed as soon as data get changed. What should i do to achieve this?

http://docs.meteor.com/#/full/observe

Check this out: http://docs.meteor.com/#/full/observe

var cursor = ThePlayers.find();
var cursorHandle = cursor.observeChanges({
  added: function (newDoc) {
    console.log("doc added: " + newDoc);
  },
  changed: function (newDoc, oldDoc) {
    console.log(oldDoc + " changed to: " + newDoc);
  },
  removed: function (oldDoc) {
    console.log("doc removed: " + oldDoc);
  }
});

You can also check out http://docs.meteor.com/#/full/observe_changes which is geared towards differences.

You can run this code explicitly on the client to fire your method only on client side changes.

1 Like

May i ask you what you want to do with the fire function ?
(beware of trying to go back to procedural programming)

well,i’m trying to run a countdown clock with that fire() function whenever data changes.

There’s an easier way to do that.

<template name="players">
  {{#each players}}
    {{> player}}
  {{/each}}
</template>

<template name="player">
  {{name}}
</template>

Template.players.helpers({
  players: function() {
    return ThePlayers.find();
  }
})

Template.player.onRendered(function(){
  fire();
})

This kind of setup fires the fire() function every time a player is rendered, either new or changed on the page.

2 Likes

Or even :

Template.players.helpers({
  players: function() {
    fire();
    return ThePlayers.find();
  }
})
1 Like