Mcope
Mcope

Reputation: 781

Meteor - Making DOM Changes from Helpers

Is it a good practice to make DOM changes from Meteor helpers? I'm currently relying on a javascript function to run inside the Meteor helper which makes the function run every time a collection data change occurs.

I know there is Tracker.autorun() but as far as I know, Tracker.autorun() only works for Session variables and does not work for collection data changes.

My current ways so far has not failed me or caused any problems but I'm not 100% sure if this was how Meteor was meant to be used.

Code Example

Template.page_body.helpers({
    orange: function() {
        do_some_rand_function()
        return this.name
    }
})

This code will make sure that do_some_rand_function() is ran every time this.name changes (this.name is a variable gotten from a Mongo Collection, therefore it is reactive).

Upvotes: 1

Views: 384

Answers (1)

David Weldon
David Weldon

Reputation: 64312

No. Helpers should not have side effects (such as manually updating your DOM, modifying the database, making an HTTP request, etc.).

Your description sounds like a good use case for adding a template autorun in the rendered callback. All autoruns are reactive computations so they will rerun if any reactive variable used within them changes (Session, Meteor.user, Collections, etc.).

Give something like this a try:

Template.myTemplate.onRendered(function() {
  this.autorun(function() {
    if (MyCollection.findOne()) {
      do_some_rand_function();
    }
  });
});

Also note that template autoruns are automatically stopped when the template is destroyed.

Upvotes: 5

Related Questions