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 blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay