How to not encapsulate Coffeescript

I don't know whether all coffeescript compilers wrap their scripts in anonymous functions, but that's what I see Rails doing. How can I disable this encapsulation?

I want to put several initializing functions in a single coffeescript file, then call one of them from an on-page <script> tag (so that each page calls a different initializer). This can't be if the initializing functions are encapsulated.

Coffeescript initializer functions:

initializerA = -> console.log 'foo'
initializerB = -> console.log 'bar'

On-page code:

<script>$(document).ready(initializerA)</script>

Sys: coffee-rails 3.2.1, Rails 3.2.3, Ruby 1.9.3

Answers


Coffeescript documentation says that all script will be wrapped in an anonymous function for the sake of encapsulation/safety. To make something accessible within the global scope do the following:

window.myvar = myvar

You can put several into a single file by doing something like this:

((Demo, $, undefined_) ->
  Demo.utils = Demo.utils or {}

  Demo.utils.bacon = (->
      alert("bacon called")
    )()

  Demo.utils.eggs = (->
      alert("eggs called")
    )()
) window.Demo = window.Demo or {}, jQuery

Then in your page just call the appropriate method:

Demo.utils.bacon();

A good explanation of this pattern can be found here.


Need Your Help

Gradle can't build Android Project in command line, aapt fails

java android gradle

I have created a basic Android project following this guide.

understanding nasm assembly for outputting characters in teletype mode

nasm bootloader

I am reading this wonderful skript on operating system programming