Is there any intrinsic support for namespacing in coffeescript?
Adequate namespacing seems like something coffeescript could really help with although I don't seem to be able to find anything to suggest that there is support for this.
I prefer using this pattern for "namespacing". It isn't really a namespace but an object tree, but it does the job:
Somewhere in the startup of the app, you define the namespaces globally (replace window
with exports
or global
based on your environment.
window.App = Models: {} Collections: {} Views: {}
Then, when you want to declare classes, you can do so:
class App.Models.MyModel # The class is namespaced in App.Models
And when you want to reference it:
myModel = new App.Models.MyModel()
If you don't like the global way of defining namespaces, you can do so before your class:
window.App.Models ?= {} # Create the "namespace" if Models does not already exist. class App.Models.MyModel
A way to make it simple to reference the class both in it's own "namespace" (the closed function) and the global namespace is to assign it immediately. Example:
# Define namespace unless it already exists window.Test or= {} # Create a class in the namespace and locally window.Test.MyClass = class MyClass constructor: (@a) -> # Alerts 3 alert new Test.MyClass(1).a + new MyClass(2).a
As you see, now you can refer to it as MyClass
within the file, but if you need it outside it's available as Test.MyClass
. If you only want it in the Test namespace you can simplify it even more:
window.Test or= {} # Create only in the namespace class window.Test.MyClass constructor: (@a) ->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With