CoffeeScript event handlers only working after page refresh


I was able to find a resolution on StackOverflow to fix an event handler.

I initially opted to added $(document).ready(...) and $(document).on('page:load', ...) handlers as follows:

ready = ->
  $('form').on 'click', '.clickable_class', (event) ->
    # doStuff

# added lines:
$(document).ready(ready)
$(document).on('page:load', ready)

However, another answer recommended adding the jquery-turbolinks instead. Browsing the source code, it appears that this gem effectively auto-registers those handlers instead.

After installing jquery-turbolinks, I was able to add require jquery.turbolinks to my app/assets/javascripts/application.js manifest:

//
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require turbolinks
//= require_tree .

With that, my script could go back to:

$ ->
  $('form').on 'click', '.clickable_class', (event) ->
    # doStuff

# added lines:
$(document).ready(ready)
$(document).on('page:load', ready)

%d bloggers like this: