Search code examples
meteormeteor-tracker

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


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.


Solution

  • 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")
    }