Nearpoint
Nearpoint

Reputation: 7362

Meteor: Use in file variables to keep track of state, or use Session?

Currently in my Meteor app, I have a boolean variable at the top of my layout file that keeps track of wether the user has closed the menu in desktop view.

var closedMenuInDesktopView = false 

Also in another point in my app I use a boolean variable at top to keep track of wether the app is currently saving or not.

var saving = false

Everything in my app is working ok but I notice in the example Meteor apps, they use the Session to keep track of state variables within the app. Is it better to do it this way instead of putting javascript variables at the top of the file that can hold value?

Upvotes: 1

Views: 272

Answers (2)

David Weldon
David Weldon

Reputation: 64312

For template code, I think you have three choices:


Session

advantages

  • Reactive
  • State is restored after a hot code push (HCP)

disadvantages

  • Pollutes the global namespace
  • Doesn't work if you have more than one instance of your template.

use when

  • You need reactive state across an HCP
  • You need to preserve state after a template is destroyed. For example if you want to remember your last search on your posts page when you come back to it.

Scoped Reactivity

advantages

  • Reactive
  • Promotes code isolation and reuse

disadvantages

  • State is not restored after an HCP
  • Slightly more verbose than Session

use when

  • You want to use a Session variable, but don't care if you lose state after the template is destroyed. In my case, that's most of the time.

Regular variable (file scope)

advantages

  • Simple

disadvantages

  • Not reactive. This usually implies a lot more jQuery code.
  • Doesn't work if you have more than one instance of your template.

use when

  • You need a constant.
  • You need a non-reactive state for a singleton template. For example, tracking if a function has ever run before.

Upvotes: 3

Neil
Neil

Reputation: 2147

Variables that you declare with var are only accessible from within that file. This is much more manageable as your application grows.

Session variables have the advantage of being reactive. They often appear in examples because they have clean syntax, and trigger DOM updates. It's best to limit using session variables for the same reasons you avoid globals.

If you don't need reactivity, stick with your locals. If you need a few reactive variables, use Session. Otherwise, have a look at Deps.Dependency to learn how to make your own reactive variables.

Upvotes: 1

Related Questions