Joelio
Joelio

Reputation: 4691

rails 4 turbolinks multiple bindings

There are similar questions to this, but they all seem to be caused by javascript tag in body, in my case mine is in the head. I also cant move my js outside of the page change block (I don't think I can at least)

I am following rails convention by having all my js in each file according to the resource and including them in application.js.

My js is in my layouts file in the head:

<!DOCTYPE html>
<html> 
 <head>
   <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

My files all follow the suggestion in the rails documentation to use page change events: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks

Here is an example js file (report.js - I use coffee script)

load_reports = ->
      table = $('#reports').DataTable()
      company_input_field = $('#rc-cn-st-input')
      company_input_field.on 'keyup change', ->
        table.column(2).search(@value).draw()
        return

$(document).on('page:change', load_reports)

This all works great, until I use the browser back button. Once I do that, I get the event fired 2 times for each click. How do I fix this and what is the convention to follow?

In other cases I moved my js outside the page change block and did:

$(document).on 'click', 'td.details-control', ->
  # do something

But this doesn't seem practical in the case above, the jquery data table I am referencing is only on one page, and only needs to be setup when I am on that page.

I did look at .off() function, but couldn't figure out how to use it in this case, everything I tried seem to either remove the active listener or fail.

Upvotes: 7

Views: 572

Answers (1)

user7252292
user7252292

Reputation:

Try using

$(document).on('turbolinks:load', load_reports) 

instead of

$(document).on('page:change', load_reports). 

That is what worked for me, it only loaded the page once.

By the way this is for rails 4.2 and above https://stackoverflow.com/a/38457941/7252292

Upvotes: 1

Related Questions