DEV Community

Joseph Kristofzski
Joseph Kristofzski

Posted on

JavaScript Event Listeners, with Turbolinks and AJAX

What best practices do you follow to maintain a clean, logical set of initializers in a Rails app, taking Turbolinks and AJAX into account?

I've seen whole app initializes and single function listeners while looking through various open source apps. Some big Ruby on Rails app are set up like this:
https://github.com/forem/forem/blob/main/app/assets/javascripts/base.js.erb
https://github.com/gitlabhq/gitlabhq/blob/master/app/assets/javascripts/main.js

I've been primarily working on smaller Rails apps, and I've found it easiest to set up standalone listeners, similar to this:

// Turbolinks and AJAX listeners
$(document).on('turbolinks:render ajaxSuccess', function () {
  some_function();
}); 

// Document ready
// (Older versions of jQuery let me put ready in the first listener)
$(document).ready(function() {
  some_function();
});
Enter fullscreen mode Exit fullscreen mode

Click and change listeners are added similar to this:

$(document).on('click', '.my-class', function() {
  some_function();
});
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more