overwatering.org

blog

about

Building a Calatrava app means writing a lot of CoffeeScript. Here’s a small tip to make that CoffeeScript read even better than it already does. When you’re writing a function that takes a callback as an argument, try passing the callback a little differently.

radar.repository.get
  quad: "languages"
  ifSuccess: (radar) ->
    views.languageQuad.render(presenter.languages(radar))
  elseFailed: ->
    alert 'Could not load languages.'

This function, get, would be implemented to look for ifSuccess and elseFailed as keys in an options hash.

radar.repository.get = ({quad, ifSuccess, elseFailed}) ->
  $.ajax.get "/#{quad}",
    success: (data) -> ifSuccess(data)
    failure: (error) -> elseFailed(error)

Though I’ve never written any SmallTalk, I believe this is inspired by that language. Effectively what you’re doing is defining a new control flow construct, so name it as such. The call to radar.repository.get now reads as a statement of the intent for all outcomes.

It’s a small thing, but it does feel much clearer.

Oh, and thanks to CoffeeScript’s object destructuring syntax, prefer a single options hash over parameter lists.