issue with Javascript in Rails View

前端 未结 1 939
温柔的废话
温柔的废话 2021-01-16 17:59

In my Rails View template, I\'m using some jQuery for tabbed panels functionality:

... content ommitted
相关标签:
1条回答
  • 2021-01-16 18:14

    Turbolinks

    The likely issue you have will be that you're trying to load the $(document).ready function with Turbolinks running.

    This simply won't work (if you're using Turbolinks), as since Turbolinks refreshes only the <body> tag of your page, it will typically prevent your JS from binding to the various elements in the DOM, as the JS has not been reloaded

    The way to fix this is to develop your JS around Turbolinks (using Turbolinks' event handlers):

    #app/assets/javascripts/tabbed_panels.js
    var new_items = function() {
      $('.accordion-tabs-minimal').each(function(index) {
         $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
      });
    
      $(document).on('click', '.accordion-tabs-minimal li > a', function(event) {
         if (!$(this).hasClass('is-active')) {
          event.preventDefault();
          var accordionTabs = $(this).closest('.accordion-tabs-minimal')
          accordionTabs.find('.is-open').removeClass('is-open').hide();
    
          $(this).next().toggleClass('is-open').toggle();
          accordionTabs.find('.is-active').removeClass('is-active');
          $(this).addClass('is-active');
         } else {
          event.preventDefault();
        }
      });
    });
    
    $(document).on("page:load ready", new_items);
    

    This should allow your tabs to be populated on page load, regardless of whether Turbolinks is operating or not.

    --

    Unobtrusive JS

    Something else to consider (you've already done this), is that you really need to use unobtrusive javascript in your application.

    Unobtrusive JS basically means that you're able to abstract your "bindings" from your page to your Javascript files in the asset pipeline. There are several important reasons for this:

    • Your JS can be loaded on any page you want (it's DRY)
    • Your JS will reside in the "backend" of your app (won't pollute views)
    • You'll be able to use the JS to populate the various elements / objects you want on screen

    It's always recommended you put your JS into separate files - including in the views sets you up for a big mess down the line

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