How do I create a reactive dependency on a reactive object field which may not exist yet?

305 views Asked by At

Given an object full of good reactivity,

var obj = {
  foo : new ReactiveVar(0),
  bar : new ReactiveVar(0)
};

I can easily react to these fields with a Tracker computation:

Tracker.autorun(function logObj() {
  console.log('obj.foo is:', obj.foo.get());
  console.log('obj.bar is:', obj.bar.get());
});

However, if I know that at a later date obj.baz is going to be defined and I also want to react to it as soon as it is defined I can't do that:

Tracker.autorun(function logObj() {
  console.log('obj.foo is:', obj.foo.get());
  console.log('obj.bar is:', obj.bar.get());
  if(obj.hasOwnProperty('baz')) console.log('obj.baz is:', obj.baz.get());
});

This happens because if it runs without obj.baz being defined then it won't add a dependency over it and thus won't rerun if it appears or changes. The only way obj.baz will be reacted unto is if foo or bar invalidate the computaton while baz is defined, thus calling the .get() and creating the dependency.

How can I react to the creation of a yet non-defined object field? I would prefer the answer being in ES5, but I am okay with ES6 or ES7.

0

There are 0 answers