Kostanos
Kostanos

Reputation: 10404

Watch if variable changed in Meteor

I found meteor variable watcher and I use it like this:

Template.restaurantMap.onCreated(function() {
  this.location = ReactiveVar;

  this.watch("location", function(value){
    console.log('value changed', value);
  });
});

It works perfectly. But, is there any Meteor's way to watch ReactiveVar?

I need to watch only one ReactiveVar, not the entire list of attached to Template. And I need to watch it separately from Meteor's template, helpers etc..

I need my own call back in case if variable changed.

Upvotes: 3

Views: 2679

Answers (2)

David Weldon
David Weldon

Reputation: 64312

You can just use an autorun, which is a built-in way to create a custom reactive context (function that runs whenever a reactive variable changes). Here's an example:

Template.restaurantMap.onCreated(function() {
  this.location = new ReactiveVar;

  var self = this;
  this.autorun(function() {
    return console.log('location changed!', self.location.get());
  })
});

Upvotes: 8

Jordan Speizer
Jordan Speizer

Reputation: 573

Any ReactiveVar that is within a reactive computation is automatically watched by meteor. Reactive computations include:

  • Template helpers
  • Iron router hooks
  • Tracker.autorun
  • this.autorun

For me, template helpers being reactive is almost always sufficient. When it's not, I use Tracker.autorun or this.autorun (from within the templates onRendered method) instead.

Upvotes: 1

Related Questions