How should I require turbolinks in `application.js` in my Rails 5 application

1.3k views Asked by At

I am building a relatively new Rails 5 application. I've been using the bootsy gem and I've been experiencing a problem where the wysiwyg will not show on the page until after a page refresh. After playing around for a while, I discovered that if I removed turbolinks from my application.js, the wysiwyg appears first time ( without a page refresh ). Can anyone tell me how I should be requiring turbolinks into my application.js. Thanks in advance.

application.js:

//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require bootstrap-sprockets
//= require bootsy
//= require turbolinks
//= require_tree .

application.scss:

@import "bootstrap-sprockets";
@import "bootstrap";
@import "bootsy";
@import "articles";

gemfile:

source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '5.0.0'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.15'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

gem 'jquery-turbolinks'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'simple_form'

gem 'bootstrap-sass'

gem 'bootsy'

I'm using simple_form in combination with bootsy so my form looks something like this:

<%= simple_form_for @article, url: action_path do |f| %>
  <%= f.input :title %>
  <%= f.input :body, label: "Article Body", as: :bootsy %>
  <%= f.submit %>
 <% end %>

2

There are 2 answers

0
JonSayer On BEST ANSWER

So after a bit of playing around I found a solution. I added document.addEventListener('turbolinks:load', Bootsy.init); to my application.js and this solved the issue.

2
Ahmad Al-kheat On

You need to use the turbolinks:load event like this :

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

function ready() {
  //your code here
}

Your require is fine.

That's it.