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

前端 未结 19 1565
忘了有多久
忘了有多久 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:35
    $(document).ready(ready)  
    
    $(document).on('turbolinks:load', ready)
    
    0 讨论(0)
  • 2020-11-21 07:39

    Either use the

    $(document).on "page:load", attachRatingHandler
    

    or use jQuery's .on function to achieve the same effect

    $(document).on 'click', 'span.star', attachRatingHandler
    

    see here for more details: http://srbiv.github.io/2013/04/06/rails-4-my-first-run-in-with-turbolinks.html

    0 讨论(0)
  • 2020-11-21 07:39

    Instead of using a variable to save the "ready" function and bind it to the events, you might want to trigger the ready event whenever page:load triggers.

    $(document).on('page:load', function() {
      $(document).trigger('ready');
    });
    
    0 讨论(0)
  • 2020-11-21 07:39

    Tested so many solution finally came to this. This many your code is definitely not called twice.

          var has_loaded=false;
          var ready = function() {
            if(!has_loaded){
              has_loaded=true;
               
              // YOURJS here
            }
          }
    
          $(document).ready(ready);
          $(document).bind('page:change', ready);

    0 讨论(0)
  • 2020-11-21 07:41

    I found the following article which worked great for me and details the use of the following:

    var load_this_javascript = function() { 
      // do some things 
    }
    $(document).ready(load_this_javascript)
    $(window).bind('page:change', load_this_javascript)
    
    0 讨论(0)
  • 2020-11-21 07:42

    I found my functions doubled when using a function for ready and turbolinks:load so I used,

    var ready = function() {
      // you code goes here
    }
    
    if (Turbolinks.supported == false) {
      $(document).on('ready', ready);
    };
    if (Turbolinks.supported == true) {
      $(document).on('turbolinks:load', ready);
    };
    

    That way your functions don't double if turbolinks is supported!

    0 讨论(0)
提交回复
热议问题