How do you use global Coffeescript variables on client startup in Meteor?
coffeescript, meteor
Solution
It has to do with the order in which the source files are evaluated. For all the details, have a careful read of this section of the docs. You can play a number of games with file names and locations in order to change their load order:
- change the file names so they appear in alphabetical order
- put the files that need to be loaded first in a subdirectory
- put the files that need to be loaded first in a `lib` directory
In this particular case, however, you can just delay the activation of the subscription, by doing something like:
Meteor.startup ->
Meteor.subscribe 'data', x
or
Tracker.autorun ->
if Meteor.userId()
Meteor.subscribe 'data', x
Tricks like these can be used to execute code after all of the source files has been evaluated.
Problem
In `lib.coffee` I have `@x = 1`. In `client.coffee` I have `Meteor.subscribe('data', x)`. When the page loads, I get the error in the console: `Uncaught ReferenceError: x is not defined` However, after the page has finished loading, and I type `x` in the console, it is recognized as a global variable with value 1.