LoginSignup
5
5

More than 5 years have passed since last update.

画面遷移時にJSがロードされないとき `turbolinks:load`イベントをバインドする

Posted at
  • Rails (5.1.6)
  • turbolinks (5.2.0)
  • turbolinks-source (5.2.0)

参考

解決手順

  • 'data-turbolinks-track': 'reload' を使用していた
  • ページ遷移時、JSがロードされなかった
  • jquery:document.readyturbolinks:load イベントをバインドすることでJSのロードが必ず実行されるようになった
application.html.haml
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'

変更したところ $(document).on 'turbolinks:load'

以下は、マークダウンのプレビューを更新させるCoffee Scriptです。

  1. マークダウン本文のkeyupイベントを監視させて、
  2. マークダウン結果を要求し
  3. #preview_by_ajaxを更新させる

のようなことをやっています。
$.debouncekeyupイベントの間引きをおこなってくれるjQueryプラグイン。便利です。

app/assets/javascripts/markdowns.coffee
- $ ->
+ $(document)
+    .on 'turbolinks:load', ->
      $('#item_body')
          .on 'keyup', $.debounce( 500, ->
              content = $(this).val()
              $.ajax({
                  url: "/markdown/preview",
                  type: "GET",
                  data: { content : content },
                  dataType: "html",
                  success: (data) ->
                    $('#preview_by_ajax').html(data)
              }))
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5