I recently processed my JS code and came across this template:
APP = (function() { var x,y,z; function foo() {} function bar() {} return {x:x, y:y, z:z, foo:foo: bar:bar}; })();
The advantage of this is that it creates non-global variables with functions that have access to everything that is defined in APP . This way APP.foo can access x, y, z and the bar without entering APP.bar() , APP.x , etc. Everything can also be obtained globally using APP.bar() , APP.x , etc. You can also nest them:
APP = (function() { var x,y,z; function foo() {} function bar() {} var WIDGETS = (function() { var a,b,c; function hello() {} function world() {} return {a:a, b:b, c:c, hello:hello, world:world}; })(); return {x:x, y:y, z:z, foo:foo: bar:bar, WIDGETS:WIDGETS}; })();
So WIDGETS will have access to variables in APP , but not vice versa ( APP.WIDGETS.hello can use foo() , but APP.foo should use WIDGETS.hello() ).
I tried to create this template using ERB (I'm on Rails), but it turned out to be dirty. So I'm thinking of writing a small source for the source for this - something like CoffeeScript (with a minimal difference / extended SASS language philosophy) that just compiles several functions for alternative javascript.
I just want a shorthand.
For example, this will compile for my second code above:
Simple and small - you just don’t need to track variables. I would also like to split the namespace this way (so that I can split it into multiple files):
APP = NAMESPACE(function() { var x,y,z; function foo() {} function bar() {}
Any thoughts on how to do this? I'm not sure about everything, but I think that if it existed, I would like Javascript to be much larger.