I have a Rails app, I recently updated to 5.0.0.RC1
. Most of the transition went smooth, but I'm having some trouble with the new Turbolinks. In my app I for example use this gem:
gem 'chosen-rails'
My application.js
file looks like this:
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require best_in_place
//= require tether
//= require bootstrap
//= require chosen-jquery
//= require_tree .
//= require turbo links
When I click on a link and render a view my chosen-query
(best_in_place
doesn't work as well) doesn't work in the initial load, but if I make a hard refresh of the page then it works. Below is an image of the result I'm getting:
And here is an image of how I want it to look:
Again, the expected look works if I make a hard refresh of the page, but not after a regular redirect_to ...
The code for my dropdown looks like this:
= select_tag :screen, options_from_collection_for_select(@screens, "id", "name"), id: "screen-selection", prompt: "Jump to screen", class: 'form-control chosen-select', style: "max-width: 250px !important"
After a redirect_to
it results in the following HTML:
<select name="screen" id="screen-selection" class="form-control chosen-select" style="max-width: 250px !important">[...]</select>
... and after a hard page reload I get this:
<select name="screen" id="screen-selection" class="form-control chosen-select" style="max-width: 250px !important; display: none;">[...]</select>
<div class="chosen-container chosen-container-single" style="width: 190px;" title="" id="screen_selection_chosen"><a class="chosen-single"><span>Jump to screen</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off"></div><ul class="chosen-results"><li class="active-result result-selected" data-option-array-index="0" style="">Jump to screen</li><li class="active-result" data-option-array-index="1" style="">tests</li></ul></div></div>
In a .coffee
file I try to initialise chosen
like this:
# enable chosen js
$('#screen-selection').chosen({
width: '190px'
})
Any ideas on what I'm doing wrong?
With turbolinks the javascript is only loaded once. On the hard refresh chosen
works because the entire page is re-rendered. Once you click a link, turbolinks hijacks the request and turns it into an ajax one (instead of a full page refresh). Once the request comes in, turbolinks only replaces the body
of the page, leaving the JS in the same state it was.
To fix this you will need to wrap your chosen initializer in the turbolinks:load
event like so
$(document).on('turbolinks:load', function() {
$('#screen-selection').chosen({
width: '190px'
})
})
For more information, see https://github.com/turbolinks/turbolinks#installing-javascript-behavior