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?

5
  • What's your question? What do you expect to happen? What actually happens? Commented Jan 24, 2013 at 16:42
  • possible duplicate of CoffeeScript & Global Variables Commented Jan 24, 2013 at 16:45
  • @yo () -> console.log("yo") appears to be the solution. Commented Jan 24, 2013 at 16:46
  • You forgot to export the yo symbol. Commented Jan 24, 2013 at 16:47
  • @Shmiddty i'm not sure it's a dupe. Commented Jan 25, 2013 at 1:15

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

@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.
Updating the CoffeeScript and recompiling it is generally preferable to letting the generated file go out of sync with the original source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.