11 5 / 2011

How CoffeeScript makes jQuery more fun than ever

UPDATE There’s also a brand new book about CoffeeScript that will be released some time in June. It includes a whole chapter dealing with jQuery. Check it out!

When I first started to work with jQuery a couple of years ago it felt as if I reached programmer heaven. It reduces the amount of required code substantially and makes working with the DOM a breeze. Implementing functionality feels so much easier. Although new frameworks emerge these days that are more suited for rich frontend development, I do not want to imagine a developer life without jQuery anymore. Can you relate? Cool :)

Enter CoffeeScript. It’s the same story all over again and is just as addictive. After writing a few lines of code you do not want to go back to plain old Javascript. CoffeeScript is packed with features. Combine them with jQuery and you’ll find new delights.

This post’s intention is to spread the word about CoffeeScript even further and to show how beautifully CoffeeScript and jQuery work together.

Iterate like a boss

CoffeeScript offers you a lot of awesome ways to iterate over arrays. The great thing about this is that these work together with jQuery objects. One line of beautiful CoffeeScript…

formValues = (elem.value for elem in $('.input'))

…is compiled into Javascript:

var elem, formValues;
formValues = (function() {
  var _i, _len, _ref, _results;
  _ref = $('.input');
  _results = [];
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    elem = _ref[_i];
  return _results;

To be honest, the fact that this works is scary at first. But once you start to use and embrace CoffeeScript’s magic, you gonna love it.

Bind methods on the fly

Using the fat arrow => inside of a jQuery callback saves you the hassle of manually binding your method to an object. Consider this piece of CoffeeScript:

object =
  func: -> $('#div').click => @element.css color: 'red'

And have a look at the compiled Javascript output:

var object;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
object = {
  func: function() {
    return $('#div').click(__bind(function() {
      return this.element.css({
        color: 'red'
    }, this));

In this scenario @element is referencing an jQuery element that has been assigned to the object somewhere else in the code. For example by running object.element = $('#some_div').

Every function that is defined using the fat arrow => is automatically bound to the object that is referenced through this. Yes. I know. It’s awesome.

Call functions like it’s 2011

Have a look at this:

  new_title: input.val()
  id: something
  -> alert('done')

With CoffeeScript you can easily distribute arguments of methods with long signatures such as $.post() and $.animate() over multiple lines. Commas and curly brackets are optional. This adds to the readability of many of jQuery’s method calls.

Here is another example:

  width: '+20px'
  opacity: '0.5'

Yum! Note that if the first argument is an anonymous object you can even omit the parenthesis of the method call.

Sexy initializer

When I started to use jQuery this was the way I initialized applications:

$(document).ready(function() {

With a newer version of jQuery and CoffeeScript this has evolved to much sexier code:


While the function definition syntax of CoffeeScript is awesome in itself, being able to use it in places like these feels even better. Generally you’ll find that all function calls that require callbacks are so much easier to write using CoffeeScript.

To read more about CoffeeScript visit the official site.

If you have more examples how CoffeeScript and jQuery work together I’d love to see them.

Permalink 59 notes Comments

blog comments powered by Disqus