Can I specify what session variables a Tracker.autorun() function depends on?

603 views Asked by At

I currently have a piece of code similar to this:

Tracker.autorun(function() {
    var foo = Session.get("foo")
    var bar = Session.get("bar")
    if (bar)
      console.log("foo changed and bar is set")
    else
      console.log("foo changed and bar is not set")
}

This code fails because the console prints one of the foo changed messages even when only bar changes.

I have to use both foo and bar inside my Tracker.autorun(), without it running whenever bar changes, and I want to do this by telling ´Tracker´ not to track bar or if possible by asking Tracker what set off the recompute, instead of separating the function into different autorunning functions or by manually keeping tabs on what Session variables have changed.

3

There are 3 answers

2
leinaD_natipaC On BEST ANSWER

As it turns out, this question has already been answered before.

The answer is to use Tracker.nonreactive(). The fixed code from my question would be:

Tracker.autorun(function() {
    var foo = Session.get("foo")

    var bar = Tracker.nonreactive(func() {
        return Session.get("bar")
    })

    if (bar)
      console.log("foo changed and bar is set")
    else
      console.log("foo changed and bar is not set")
}
3
MrE On

You can split the autorun functions:

Tracker.autorun(function() {
    var foo = Session.get("foo")
    // will run when foo changes
}


Tracker.autorun(function() {
    var bar = Session.get("bar")
    // will run when bar changes
}
1
imkost On

What about this approach?

var foo;
var bar;

Tracker.autorun(function() {
    foo = Session.get("foo")
    bar = Session.get("bar")
});

Tracker.autorun(function() {
    // Track for changes of `foo`
    Session.get("foo");

    if (bar)
        console.log("foo changed and bar is set")
    else
        console.log("foo changed and bar is not set")
});

UPD. Oh, I see, you already have found a solution. Anyway, I will leave my answer here, maybe somebody will find it useful.