1

I have CoffeeScript that looks like the following:

myfunctionname = (foo, bar, baz) ->
    alert("I am here")
    return

This is supposed to be the way to declare a function in coffee script. (according to js2coffee.org and others)

This gets converted into the following:

(function() {
  var myfunctionname;

  myfunctionname = function(foo, bar, baz) {
    alert("I am here");
  };
}).call(this);

The problem with this is that when I try to include this js file into a view and access my myfunctionname method, it does not exist. It is probably out of scope.

Thus, CoffeeScript does not convert into a usable format for me. I need the following output format:

function myfunctionname (foo, bar, baz) {
  alert("I am here");
};

This format allows me to include the functions where I need them.

Is there any way of achieving this in CoffeeScript? Or should I consider dropping CoffeeScript altogether?

Community
  • 1
  • 1
Automatico
  • 12,420
  • 9
  • 82
  • 110

1 Answers1

1

Coffee-script surround all your statements with an anonymous function call, which is a good practice for avoiding polluting the global namespace.

If you want to avoid this behavior, you can manually attach your function to the window namespace (which is the global namespace in DOM) :

myfunctionname = (foo, bar, baz) ->
    alert("I am here")
    return

window.myfunctionname = myfunctionname

If you plan to this with several functions, I suggest you to add one single object in window, and then add all your specific exported functions into.

window.MyApp = {}
window.MyApp.myfunctionname = ...
Anthony Garcia-Labiad
  • 3,531
  • 1
  • 26
  • 30
  • Awesome. Thanks! I agree that it would clutter the global namespace, but very nice to be able to selectively do so. – Automatico Feb 10 '14 at 16:48