Where do I put my constants correctly in Meteor
I usually follow
To give an example: I have records in a database with a persistent GUID that I need to specify at many points in my application. Until now, I just bind constants to the appropriate set, so in collections/myCollectionWithGuids.coffee
it it would say:
@MyCollectionWithGuids = new Meteor.Collection "myCollectionWithGuids"
@MyCollectionWithGuids.CONSTANT_ID = "8e7c2fe3-6644-42ea-b114-df8c5211b842"
This approach worked great until I use it in the following snippet located at client/views/myCollectionWithGuidsView.coffee
where it says:
Session.setDefault "selectedOption", MyCollectionWithGuids.CONSTANT_ID
... which is not available because the file is loaded before the Collections are created.
So where should I put my constants then so that they always load first without hacking into a bunch of subdirectories?
You can rely on the fact that directory names are lib
always processed first when it comes to load order.
So, I would suggest that you organize your code like this:
lib/collections/collection.js client/views/view.js
This will be fine for your specific use case, but you might find cases where you need to use lib
in your client directory, and also as a stack of load order rules (subdirectories are loaded first), this will load to the folder lib
under the root of your project.
At the moment, the only way to get full control over the load order is to rely on the package API, so you'll have to make your code snippet a local package of your application (living in packages
your project root directory ).
This makes sense because you seem to have a collection and a view related in some way, plus splicing your project into a bunch of co-located local packages is usually an elegant design pattern.
Building a local package is really easy now that Meteor 0.9 provides documentation for the API package.js
.
http://docs.meteor.com/#packagejs
I would put your collection definitions in a directory lib
. The file structure documentation explains that all files in the directory lib
are loaded before any other files, which means that your variable will be defined when you try to use it in your client code.
Generally speaking, you always want your collections to be defined before anything else in your application is loaded or executed, as your application is most likely heavily dependent on using a collection cursor.