2

I have recently started using coffeescript with Rails and I am finding that sometimes the generated javascript does not get the function safety wrapper.

Here is a sample project demonstrating it.

For example, this CS code, in index.js.coffee:

class Foo
  afunc: ->
    alert("afunc")

Correctly becomes:

(function() {
  var Foo;

  Foo = (function() {

    function Foo() {}

    Foo.prototype.afunc = function() {
      return alert("afunc");
    };

    return Foo;

  })();

}).call(this);

But this code, from other.js.coffee:

class App.Func
  ouch: ->
    alert("ouch")

becomes this un-wrapped version

  App.Func = (function() {

    function Func() {}

    Func.prototype.ouch = function() {
      return alert("ouch");
    };

    return Func;

  })();

It seems to be due to the "App." prefix - which I can see affects naming/scope - but why is coffeescript compiling it differently...

App is defined in setup.js.coffee, like this:

window.App =
  Models: {}

Which also does not get wrapped, unless I add a class into that file too.

I am sure it must be my misunderstanding - so thanks in advance for the pointers to the manual :).

EDIT: I created this question as I thought it might be behind some issues I was having with my backbone/coffeescript app, but it seems that it was not. As the class is linked to a public/global thing "App", it seems to work wrapped or not. Still would be useful to know why its happening - is it by design?

Chris Kimpton
  • 5,546
  • 6
  • 45
  • 72
  • 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); see my answer on that question. – Trevor Burnham Nov 16 '11 at 14:53
  • Many thanks for the comment, but I must be missing something obvious, those questions/answers say that the generated code will ALWAYS be wrapped in a function unless the default_bare setting is used. The problem I have is that I am not using that setting and only some code is being wrapped in a function. Is the compiler working out that "App" is a global and not wrapping those bits of code? – Chris Kimpton Nov 16 '11 at 16:28

1 Answers1

1

The "function safety wrapper" feature you are using works to prevent local variables from being set on the global namespace. Since setting an object property (App.Func) doesn't affect the global namespace, the declaration is not wrapped in a function.

Marcel M.
  • 2,376
  • 2
  • 18
  • 24