4

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

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
JellicleCat
  • 28,480
  • 24
  • 109
  • 162
  • possible duplicate of [How can I use option "--bare" in Rails 3.1 for CoffeeScript?](http://stackoverflow.com/questions/6099342/how-can-i-use-option-bare-in-rails-3-1-for-coffeescript) – Trevor Burnham Jun 14 '12 at 14:50
  • @TrevorBurnham, similar indeed. However, I couldn't find that question, using search terms pertinent to this question and its answers, so this one must have some value. – JellicleCat Jun 17 '12 at 19:43
  • That's the reason why duplicates are closed rather than being deleted: It allows them to point the way to a more canonical question. – Trevor Burnham Jun 17 '12 at 21:15

2 Answers2

7

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
JellicleCat
  • 28,480
  • 24
  • 109
  • 162
2

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.

flynfish
  • 5,857
  • 3
  • 24
  • 33