簡體   English   中英

Rails 6:渲染部分后執行 JS function

[英]Rails 6: execute a JS function after rendering partial

Rails & Javascript 初學者在這里,

在一個培訓項目中,我使用 JQuery 使flash消息在幾秒鍾后消失。訪問者會發送 AJAX 請求將產品添加到他的購物車,然后 flash 部分“已添加到購物車”出現並在幾秒鍾后自動淡出。


# application.html.erb

<div id='flash' class='flex-column'>
   <%= render partial: 'shared/flash'  %>
</div>
# shared/_flash.html.erb

<% flash.each do |key, value| %>
  <%= display_flash(key, value) %>
  <%= javascript_pack_tag 'custom/flash' %>  
  # this works, but injects the script each times the partial is rendered
<% end %>
# helpers/application_helper.rb

def display_flash(key, value)
  def display_flash(key, value)
    div_class = [flash_class(key), 'text-center fade show alert-dismissible'].join(' ')

    content_tag(:div, class: div_class) do
      content_tag(:p, value) +
      button_tag(class: 'ml-auto close', 'data-dismiss': 'alert', type: 'button') do
        content_tag(:span, '&times;'.html_safe, 'aria-hidden': 'true') +
        content_tag(:span, 'Close', class: 'sr-only')
      end
    end
  end
end
// app/javascript/packs/custom/flash.js

function closeFlash(){
  let lastAlert = $('#flash .alert:last')

  function fadeFlash() {
    lastAlert.animate( {opacity: 0}, 2000, function() {
      $(this).hide('slow', function() {
        $(this).remove()
      });
    });
  };

  setTimeout(fadeFlash, 2000)
};

closeFlash();

問題是它用不必要的<script>標簽污染了我的 DOM: 不需要的腳本標簽

這可以修復,但是是否有合適的方法在渲染(AJAX)部分后執行一個特定的 javascript function? 在我的例子中,每次呈現部分時執行位於packs/custom/flash.js中的closeFlash()

感謝您的幫助和您的時間


編輯解決方案:

來自 Amit Patel 的回答和這篇文章

// app/javascript/packs/custom/flash.js

window.closeFlash = function() {
    let lastAlert = $('#flash .alert:last')

    function fadeFlash() {
        lastAlert.animate( {opacity: 0}, 2000, function() {
            $(this).hide('slow', function() {
                $(this).remove()
            });
        });
    };

    setTimeout(fadeFlash, 2000)
};
 // app/javascript/packs/custom/flash.js window.closeFlash = function() { let lastAlert = $('#flash.alert:last') function fadeFlash() { lastAlert.animate( {opacity: 0}, 2000, function() { $(this).hide('slow', function() { $(this).remove() }); }); }; setTimeout(fadeFlash, 2000) };

它不會注入整個 function 但(我相信)最小的 javascript 代碼來調用它。

<%= javascript_pack_tag 'custom/flash' %>移動到您的布局或 application.js` 中,以便在整個應用程序中可用。

修改您的模板,例如

應用程序.html.erb

<div id='flash' class='flex-column'>
   <%= render partial: 'shared/flash'  %>
   <script>
     $(function(){
       closeFlash();
     });
   </script>
</div>

更新的方法是設置刺激 controller。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM