Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespacing in coffeescript

Tags:

coffeescript

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.

like image 311
dagda1 Avatar asked Nov 11 '11 07:11

dagda1


2 Answers

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 
like image 130
Brian Genisio Avatar answered Sep 18 '22 11:09

Brian Genisio


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) -> 
like image 29
ciscoheat Avatar answered Sep 16 '22 11:09

ciscoheat