jQuery flavored CoffeeScript
After much discussion, Rails 3.1 included CoffeeScript by default. The inclusion of CoffeeScript in Rails is a testament of the quality and popularity of CoffeeScript.
So in a Rails 3.1 application if you do - bundle exec rails g controller Pages home
You get an output like the following -
As you can see from the output above Rails will generate a .coffee file for you with the controller.
CoffeeScript is a beautiful language and enables you to write clean code and escape the nuances of JavaScript.
A function declaration in CoffeeScript is as simple as
The two keys in CoffeeScript ”-” and ”>” are enough to declare a function in JavaScript.
With these things in mind, I decided to write jQuery code in JavaScript. After all, if we intend to write JavaScript for our web application there is no escaping jQuery.
Lets say our haml/html is like
Which renders to -
Nothing much going on here. To test jQuery, all we need to write is -
That’s it!!
this translates to -
So in CoffeeScript, intializing jQuery amounts to writing ”$ ->”
Now let’s write a simple function to make a hidden div visible.
this converts to -
The CoffeeScript code above is pretty clean and self explanatory. The most important thing is that I have just written two lines of clean code (it can even be compressed to one), this typically converts to 6 lines of JavaScript (even if we forget the curly braces and the parentheses).
So go forth my friend and write your JavaScript code in CoffeeScript and make your life simpler!