I was exploring various ways of creating a namespace for my application's functions and I wasn't happy with any of the options I found. My requirements were something like:
- The namespace should be a top-level variable. I don't want to have to prefix everything with "window."
- It should be possible to add things to the namespace so that I can organize my functions into files as I see fit.
- I would like my function names to appear at the beginning of the line when I define them so it's easy to visually parse the files.
- I'm not concerned with private attributes or functions right now.
Here's what I came up with. This is a Rails 3.2 application, so I'm using the asset pipeline, but this should be easy to adapt to other frameworks.
The main manifest, which shows the proper load order:
Creating the namespace:
Adding Coffeescript functions to the namespace:
Then, you can simply call MyApp.test() from anywhere in your app.