Search code examples
javascriptnode.jsnamespacesmeteordirectory-structure

Meteor 0.8.x namespacing


Background Info

I've witnessed that Meteor wraps each file into an anonymous function to prevent filling up the global namespace.

Assume that I have a similar file structure:

  • client/
    • index.html
    • style.css
    • client.js
    • helpers/
      • somehelper.js
  • server/
    • server.js
  • models/
    • ...

My Questions

  1. How can I use objects that are in somehelper.js from the file client.js?

  2. How can I create my own namespaces? For example: client, client.helpers, models and server.


Solution

  • You're right! Each file has it's own local namespace. To define a global variable you would need to drop the leading var. A common practice to prevent polluting your global namespace is to have a single global object, e.g. App, to host all globally-scoped symbols. This object can defined in the top level lib folder to overcome some file-loading-order related issues.

    If for some reason your code depends on the file loading order, you can wrap some parts of it within Meteor.startup routine to prevent undefined-type-errors.

    Another possible solution - if like modules and stuff like that - would be to use some AMD-imitating tool for Meteor like this one for example.