2

I have the following Coffeescript in test.js

yo () -> console.log("yo")

When compiled via coffee -o public/javascripts/ -cw public/coffeescripts/, I get public/javascripts/test.js:

// Generated by CoffeeScript 1.4.0
(function() {
  var yo;

  yo = function() {
    return console.log('yo');
  };

}).call(this);

I'm trying to include this in the usual way in an HTML file:

<script src="/javascripts/test.js" type="text/javascript"></script>
<script type='text/javascript'>
  //<![CDATA[
  $(function() {
    alert('before yo');
    yo();
    alert('after yo');
  });
  //]]>
</script>

However I keep getting "Uncaught Reference Error: yo is not defined". Whats the process for actually using the javascript generated by Coffeescript?

Allyl Isocyanate
  • 13,306
  • 17
  • 79
  • 130

2 Answers2

3

In your CoffeeScript file, yo is a local variable. It is not a global variable. If you want to use that variable from another JavaScript file or from JavaScript in the HTML file, then you will need to make yo a global variable.

You can do this in the CoffeeScript file like so:

yo = -> ...

# either
@yo = yo
# or
window.yo = yo
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
2

The generated Javascript from your Coffeescript needs a tweak to export yo outside the calling context.

// Generated by CoffeeScript 1.4.0
(function(context) { // changed this line (note: context == 'this' which is being passed in at last line)
  var yo;

  yo = function() {
     return console.log('yo');
  };

  context.yo = yo; //export yo to the context.

}).call(this);

Commonly, instead of this, will you see people pass in window and/or document when the code is used in the context of a web page (as opposed to server-side Node.js calling context).

I updated the Javascript, but you can have easily used the 'module export' idiom which you can read more about here - Pattern for CoffeeScript modules

Community
  • 1
  • 1
mrk
  • 4,999
  • 3
  • 27
  • 42
  • @yo solution prevented me from tweaking the javascript, but your solution gave me some more background on the underlying issue of the coffeescript module pattern...so I upvoted as well. – Allyl Isocyanate Jan 24 '13 at 18:43
  • Updating the CoffeeScript and recompiling it is generally preferable to letting the generated file go out of sync with the original source. – yfeldblum Jan 24 '13 at 18:57