November 04, 2014
Using jQuery with CoffeeScript
CoffeeScript is a language that compiles into Javascript. It aims to abstract the difficult and awkward parts of Javascript and introduce things that are missing (in the mind of the developer). The syntax that is used by CoffeeScript
is more concise and eliminates the need for many of the parenthesis and semi-colons that you typically would need to write.
At first I found CoffeeScript a bit clunky, coming from a background of programming that doesn’t rely on indentation, but after using it more I began to find it easier and nicer to write.
Anonymous closures
The Drupal code standard for Javascript is to include your functionality in a closure which is given references to jQuery
, Drupal
and window
.
Compiled:
DOM ready
The jQuery DOM ready event can be written like:
Compiled:
Event binding + selecting elements
Elements can be selected in a few different ways, this is one place in CoffeeScript that you will require ()
(parenthesis).
Compiled:
Plugins with parameters
There are two ways you can call member functions of a jQuery element.
Compiled: