I have a class written in coffeescript, e.g.,
class Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
and I have this class as a separate file, Example.coffee
Now I want to be able to instantiate in my main javascript file like so:
d = new Example
d.render()
but the class is undefined even when it is included as a script on the page, like
<script src="Example.js></script>
<script src="main.js"></script>
How do you make the class publicly available to the main file?
You can declare your class to be globally accessible (at least for browsers) by declaring it to be in the
windownamespace:That will put
Examplestraight intowindow. You can also sayclass @Examplein most cases.By default, CoffeeScript wraps each file in a
(function() { ... })()wrapper to prevent namespace pollution. You can prevent this by supplying-bwhen compiling your CoffeeScript:but that might not be an option for you (or it might be an ugly one). The usual approach is to declare an application specific namespace somewhere before your classes are loaded:
and then namespace your classes appropriately:
Then refer to everything through the
Appnamespace.