jQuery Delegate - 07 Jun 2012

If you’re using AJAX in your views, then you’re most likely going to want to take advantage of jQuery’s delegate function. Delegate watches for events in the future, so you no longer need to call sortable, best_in_place, etc. in your AJAX responses.

Getting delegate to work is very straightforward and will require few changes to your existing code. Here are a few examples of how I’m using delegate in some of my applications.

$('span.notes').delegate 'tr.note', 'hover', ->


  $('table.notes.sortable tbody').sortable

    axis: 'y'

    handle: '.handle'

    update: ->

      $.post $('table.notes.sortable').attr( 'url' ), 

        $(this).sortable 'serialize'

$('span.notes').delegate 'td.note-completed input.checkbox', 'hover', ->

  project = $('h1.project-title').attr 'id'

  note = $(this).attr 'id'


    type: 'POST'

    url: $('td.note-completed').attr('url')

    dataType: 'script'

    data: { project_id: project, id: note }

My notes table is wrapped in a span with the class of notes. That span isn’t updated in my AJAX responses, so it’s a safe wrapper for the delegate method.

I’m using hover for the delegate function, because I find that it provides a much more responsive user experience.

Discovering delegate while reading through the jQuery docs has made my life a lot easier, and I hope it helps someone else as well. Feel free to contact me if you have any questions or input, thanks.