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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay