Rails 4: how to use $(document).ready() with turbo-links

前端 未结 19 1534
忘了有多久
忘了有多久 2020-11-21 06:52

I ran into an issue in my Rails 4 app while trying to organize JS files \"the rails way\". They were previously scattered across different views. I organized them into separ

相关标签:
19条回答
  • 2020-11-21 07:54

    Here's what I do... CoffeeScript:

    ready = ->
    
      ...your coffeescript goes here...
    
    $(document).ready(ready)
    $(document).on('page:load', ready)
    

    last line listens for page load which is what turbo links will trigger.

    Edit...adding Javascript version (per request):

    var ready;
    ready = function() {
    
      ...your javascript goes here...
    
    };
    
    $(document).ready(ready);
    $(document).on('page:load', ready);
    

    Edit 2...For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

    $(document).on('turbolinks:load', function() {
    
      ...your javascript goes here...
    
    });
    
    0 讨论(0)
提交回复
热议问题