a paragraph is clicked, you can do it with
the following CoffeeScript:
changeSize = -> alert("changing size!")
Note how I’ve defined two functions
here: an anonymous function for $(document).ready and another function
to which I give the name changeSize.
But, of course, you want to do something
a bit more complex than display an alert
dialog; you want to change the size.
When changeSize is fired, you want to
know which paragraph to change. An
event handler always is passed “this”,
that confuses many people.
One way to get the sizes to rotate is
shown in Listing 3, app.coffee. Basically,
your callback function starts off by
assigning a local variable, “text”. If this
local variable, but rather a global one,
because you used neither the “var”
keyword nor another object (for example,
myObject.text). In CoffeeScript, variables
are local, which means you cannot pollute
the global namespace accidentally.
Listing 3. app.coffee
changeSize = -> text = $(this)
if text.hasClass "small" text.removeClass "small" text.addClass "medium"
else if text.hasClass "medium" text.removeClass "medium" text.addClass "large"
else if text.hasClass "large" text.removeClass "large" text.addClass "small"
else text.addClass "large"
($ "p").addClass "large" ($ "p").live 'click', changeSize
Listing 3 shows a basic use of if/then/else
blocks. Notice there isn’t any need for
braces, begin/end statements or other
markers. Python programmers will see this
(rightly) as a vindication of semantically
significant whitespace. I just like the fact
that well-indented code is easy to read,