最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Watch if variable changed in Meteor - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Jul 20, 2015 at 20:18 Kostanos asked Jul 20, 2015 at 2:32 KostanosKostanos 10.5k4 gold badges59 silver badges69 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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());
  })
});

Any ReactiveVar that is within a reactive putation is automatically watched by meteor. Reactive putations 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.

发布评论

评论列表(0)

  1. 暂无评论