Using jQuery with CoffeeScript

I’ve been playing with CoffeeScript recently, for no other reason than to satisfy my intrigue. Of course, one of the first things I wanted to work out was how to use jQuery with my CoffeeScripts.

jQuery ready handler in CoffeeScript

As you know, all your jQuery methods should be hooked to jQuery’s .ready() event handler. If you’re averse to the odd keystroke, you’re probably already using the shorthand alternative $(function(){ });.

This can be achieved in CoffeeScript simply by using $ ->. Really, that’s it, but I personally prefer to use the slightly longer-hand jQuery -> which I think makes it a bit clearer that the following lines of your CoffeeScript are using jQuery.

So, in CoffeeScript we use:

jQuery ->
  ### your code here ###

Which in JavaScript compiles to:

  /* your code here */

Wrapping jQuery plugins in a closure

As explained in the jQuery plugin authoring guidelines, all plugins should be wrapped in a closure. Here’s the cool thing: in CoffeeScript we don’t even need to do that.

As CoffeeScript already safely wraps everything in a closure, all we need to do is set $ = jQuery at the top of our code.

So, in CoffeeScript we simply do:

$ = jQuery
$.fn.myFunction = ->
  ### your code here ###

Which in JavaScript compiles nicely to:

  var $;
  $ = jQuery;
  $.fn.myFunction = function() {
    /* your code here */

For what it’s worth, and as a bit of an aside, the benefits gained from learning and using CoffeeScript are a bit debatable if all you’re looking to do is throw a few lines of jQuery together. That said, if you are using CoffeeScript you’ll probably want to to use it with jQuery too, so hopefully these two tips will prove useful to some.