user3006927
user3006927

Reputation: 476

JavaScript is loading 3 times on Rails application

I have an ajax function that is being called multiple times on click when it should just be firing once.

$(document).on('click', '.newGameItem', function() {
    console.log('start click event');
    var apiUrl = $(this).attr('data-api-string');
    var callType = $(this).attr('data-api-post-call');
    var apiKey = $(this).attr('data-api-key');
    var dataType = $(this).attr('data-api-data-type');
    var returnValue = $(this).attr('data-return-value');
    var currentGameWrapper = $(this).parent().parent().parent();

    console.log('before api call');
    getNewItem(apiUrl, callType, apiKey, dataType, returnValue, currentGameWrapper);
    console.log('after api call');
});

This click event is inside a turbolinks load event:

$(document).on('turbolinks:load', function() {  ...  }

I put in a console.log at the top of the turbolinks load event and can confirm that the JavaScript in this file is running 3 times. I've noticed this happens when I am on this page, click a link to another page and then hit the back button to this page but it also happens when I click to the page from somewhere else in the app.

This file is being compiled through the asset pipeline and we have data-no-turbolink on the body tag (which has actually never seemed to do anything.

Any ideas why this is happening or ways to get around it? Taking turbolinks out of my app completely is not an option for me at this time.

Thank you

Upvotes: 0

Views: 374

Answers (1)

Leonel Galán
Leonel Galán

Reputation: 7167

That click event has to be outside the 'turbolinks:load' event, that's the point of attaching it to $(document) as opposed to the element. If you have it inside it will create it every time a page loads. Your javascript should look like this:

$(document).on('click', '.newGameItem', function() {
  // ...
});

$(document).on('turbolinks:load', function() {
  // ...
});

Upvotes: 1

Related Questions