the etherpros blog

Garber-Irish JS init() on Coffeescript.

If you're not familiar with the Garber-Irish method of creating javascript initialization methods, please take a moment to read this fantastic article on the subject of javascript init methods. It will really make your javascript code management significantly easier, especially if you're running the Rails 3.1 Asset Pipeline which mushes all your javascript files into one big file preventing you from easily sectioning off your javascript code on a page-by-page basis.

Garber-Irish's solution works especially well with Rails, but it depends on a somewhat verbose javascript function. I decided to go ahead and port this to Coffeescript for those of you running it. Enjoy:

this.JSRouter = {
    init: ->
      # application-wide code
    init: ->
      # controller-wide code
    show: ->
      # action-specific code  

Util = {
  exec: (controller, action) ->
    ns = JSRouter
    if controller != "" and ns[controller] and typeof ns[controller][action] == "function"

  init: ->
    body = document.body
    controller = body.getAttribute "data-controller"
    action = body.getAttribute "data-action"

    Util.exec "common"
    Util.exec controller
    Util.exec controller, action

$(document).ready Util.init

James Strong

29 May 2012