1

I have a meteor template which displays comments. I've set up a reactive template helper which returns replies when they are added by users. I'd like to trigger a function when the number of replies changes--when any user adds a new reply to the current discussion), but I'm not sure what the best way to do this is.

Currently, I have this setup as part of the template helper, but this seems really brittle.

Template.comments.helpers({
  replies: function() {
    var discussionId = Session.get("openedDiscussion");
    var replies = Replies.find({discussionId: discussionId});

    // I want this function to run every time the # of replies changes.
    foobar();
    console.log('There are is a new reply from someone else');

    return replies;
  }
}); 

I've also tried using Deps.autorun, but can't figure out how to do this with properly with the Session object. I'm also unsure where to place this in my Meteor project:

Deps.autorun(function () {
  var discussionId = Session.get("openedDiscussion");
  var replies = Replies.find({discussionId: discussionId});

  // I want this function to run every time the # of replies changes.
  foobar();
  console.log('There are is a new reply from someone else');
});

I also get this error in the console when I try to Uncaught ReferenceError: Replies is not defined

Chanpory
  • 3,015
  • 6
  • 37
  • 49
  • possible duplicate of [Meteor subscribe to a count](http://stackoverflow.com/questions/14656567/meteor-subscribe-to-a-count) – Daniel Le Mar 09 '14 at 03:35
  • is Replies available at that file? Did you make `Replies` a global variable (no `var` keyword?). Are you sure you are running it only on the client side? – imslavko Mar 09 '14 at 10:05

1 Answers1

0

Depending on your use case you could either subscribe to the collection within Deps.run to have a function rerun each time the collection changes :

Deps.autorun(function () {
  Meteor.subscribe("replies", function() {         
      var discussionId = Session.get("openedDiscussion");  // get the newly added item here depending on your business case
      if (discussionId) {
        foobar();
        console.log('There are is a new reply from someone else');
      }
  });
});

Or you could simply do this which will run the function whenever your session variable changes, whichever works better for your use case:

Deps.autorun(function () {
    var discussionId = Session.get("openedDiscussion");          
    if (discussionId) {
        foobar();
        console.log('There are is a new reply from someone else');
    }
});
arielf
  • 401
  • 2
  • 8