Listing 2. coffeescript.css
p.large { font-size: 30px; }
p.medium { font-size: 20px; }
p.small { font-size: 10px; }
for your Web page, but it also will result
in an error if you try to access the DOM,
which isn’t available outside a browser
context.) You can do this with:
coffee --compile app.coffee
The problem with this approach is that
you need to recompile your CoffeeScript
program every time you change it. A better solution probably is to tell CoffeeScript
to watch the file and compile it every
time a change is detected:
coffee --compile --watch app.coffee
Just after running this, the compiler
will run over app.coffee, producing
app.js. When you load your Web page,
app.js will run, and you should have
an alert saying “hello”.
Functions and Objects
It’s important to remember that although
CoffeeScript certainly is a different syntax
from JavaScript, it is fundamentally
the same language. This means any
function or object that you can access
from JavaScript can be accessed from
CoffeeScript, with the same name. True,
CoffeeScript does offer some shortcuts
and syntactic sugar; those basic JavaScript
objects are still around and kicking.
That’s why you could invoke the “alert”
function in app.coffee—it’s not that
CoffeeScript has defined a new function,
but rather that you’re using the same
built-in JavaScript function.
This means if you load jQuery in the
same document as a program written in
CoffeeScript, you can use jQuery from
within CoffeeScript. What does that mean?
Well, it means you can access the jQuery
object directly, often abbreviated as $. For
example, let’s change app.coffee so that it
tells you what version of jQuery you’re
using, normally available via $().jquery.
You also can do this in CoffeeScript:
alert $().jquery
Let’s do something a bit more exciting
now, using jQuery’s capabilities for easily
changing elements in the DOM based on
events that take place. For example, you
can add the “large” class to all of the
paragraph elements in your document.