Written by: steve ross on May 22nd 2011

As far as I can tell, the world didn't end yesterday. At least it looks that way, so maybe you are interested in writing a jQuery plugin in Coffeescript. It's really quite straightforward.

I wrote an editable grid plugin that creates a client-side expandable, editable grid. Here's where I started:

Creating a Plugin Skeleton

$.fn.editableGrid = (options) ->

My plugin is to be called editableGrid, so there it is, a function definition. Note that this will immediately be dropped into the jQuery namespace because it's being declared in it. More precisely, it will be in the jQuery.fn namespace.

$.fn.editableGrid = (options) ->

  this.each ->
    setupGrid $(this)

It is important no note that the iterator is indented one level below the $.fn.editableGrid stuff. In a whitespace-sensitive language when other stuff intervenes, it can be hard to understand the lexical scope when outdenting occurs.

So what we are doing is upon invocation of the plugin, applying setupGrid to each matched element. The calling sequence from your normal Javascript is:

$('table.editable').editableGrid()

Note that in my code, I used jQuery's each iterator. It could have as simply been done using Coffeescript's comprehensions:

setupGrid(matched) for matched in this

Now you have the skeleton, let's add setupGrid just to prove it works:

$.fn.editableGrid = (options) -> setupGrid = (ele) -> # Define a function before first use ele.html 'I am a table'

# Notice how, with the intervening code, the lexical
# scope of the code below becomes less clear?
this.each ->
  setupGrid $(this)

Where to Go From Here

Well, first of all, figure out a plugin that actually does something. As of right now (the day after the End of the World), there is no ecosystem for distributing Coffeescript jQuery plugins, but if enough of them pop up, I'm sure that will change.

Disclaimer

Please forgive the EODs references. The news was obsessed with the story yesterday and I found it interesting that Facebook and Twitter were "left behind" as were (obviously) some software developers. Like me and like you.