Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 329
Kostanos Avatar asked Jun 22 '26 15:06

Kostanos


2 Answers

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());
  })
});
like image 143
David Weldon Avatar answered Jun 25 '26 04:06

David Weldon


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.

like image 22
Jordan Speizer Avatar answered Jun 25 '26 05:06

Jordan Speizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!