 class MultiSelect
-  setup: (table) ->
+  callbacks: {}
+  on: (event, callback) ->
+    @callbacks[event] ||= []
+    @callbacks[event].push callback
+  trigger: (event)->
+    return unless @callbacks[event]
+    for callback in @callbacks[event]
+      callback.call(@)
+  setup: (table, options) ->
     return unless table and table.length
+    selector = @
     table.data 'multi_select', @
     @set 'table', table
+    @options = options
+    @on 'changed', options.changed if options.changed
 
     @set 'resource', table.data('resource')
     # Add an extra th to all header rows

        $(this).removeClass('checked').addClass('unchecked')
      else
        $(this).removeClass('unchecked').addClass('checked')
    record_td = $('<td></td>').addClass('selection').append(record_toggle)
    table.find('tbody tr').prepend record_td


  set: (path, value) -> @[path] = value
  get: (path) -> @[path]

  selected_count: -> @table.find('td.selection .checked').length
  total_count: -> @table.find('td.selection .checker').length

  #selected_records: -> @table.find("td.selection input:checked").map( -> $(this).parents('tr').data('record') )
  selected_records: -> @table.find("td.selection .checked").map( -> $(this).parents('tr').data('record') )
  selected_ids: -> @selected_records().map( -> @id ).toArray()
root = @
root.MultiSelect = new MultiSelect()
$.fn.multi_select = (options = {})->
  if @.hasClass('with-selection') or @.prop('tagName') is 'TABLE'
    select = new MultiSelect()
    root.MultiSelect = select
    select.setup @, options
  else
    @.find('table.with-selection').each (i, el)->
      select = new MultiSelect()
      root.MultiSelect = select
      select.setup $(el), options
  select
