Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a template helper reactive in Meteor

I am building a chat application and on my "new chats" page I have a list of contacts, which you can select one by one by tapping them (upon which I apply a CSS selected class and push the user id into an array called 'newChatters'.

I want to make this array available to a helper method so I can display a reactive list of names, with all users who have been added to the chat.

The template that I want to display the reactive list in:

<template name="newChatDetails">
  <div class="contactHeader">
    <h2 class="newChatHeader">{{newChatters}}</h2>
  </div>
</template>

The click contactItem event triggered whenever a contact is selected:

Template.contactsLayout.events({
 'click #contactItem': function (e) {
   e.preventDefault();
   $(e.target).toggleClass('selected');
   newChatters.push(this.username);
...

The newChatters array is getting updated correctly so up to this point all is working fine. Now I need to make {{newChatters}} update reactively. Here's what I've tried but it's not right and isn't working:

Template.newChatDetails.helpers({
  newChatters: function() {
    return newChatters;
  }
});

How and where do I use Deps.autorun() to make this work? Do I even need it, as I thought that helper methods auto update on invalidation anyway?

like image 790
jawad-uk Avatar asked May 03 '14 19:05

jawad-uk


2 Answers

1) Define Tracker.Dependency in the same place where you define your object:

var newChatters = [];
var newChattersDep = new Tracker.Dependency();

2) Use depend() before you read from the object:

Template.newChatDetails.newChatters = function() {
  newChattersDep.depend();
  return newChatters;
};

3) Use changed() after you write:

Template.contactsLayout.events({
  'click #contactItem': function(e, t) {
    ...
    newChatters.push(...);
    newChattersDep.changed();
  },
});
like image 125
Hubert OG Avatar answered Oct 07 '22 22:10

Hubert OG


You should use the Session object for this.

Template.contactsLayout.events({
 'click #contactItem': function (e) {
   //...
   newChatters.push(this.username);
   Session.set('newChatters', newChatters);
 }
});

and then

Template.newChatDetails.helpers({
  newChatters: function() {
    return Session.get('newChatters');
  }
});
like image 24
jacksondc Avatar answered Oct 07 '22 21:10

jacksondc