簡體   English   中英

如何確保在控制器特定的JS之后調用Rails資產管道中的JQuery腳本?

[英]How do I make sure JQuery scripts in Rails asset pipeline are called after controller-specific JS?

例如:

我有一個通用的表單錯誤處理腳本,其運行方式如下:

function default_form_method(){
    $("form[data-remote='true']").bind("ajax:error", function(evt, xhr, status, error){
        //show the errors, etc.

    })
    .bind('ajax:success', function(evt, data, status, xhr){
// clear the form, etc.

    });
}

現在,當我通過諸如index.js.erb之類的部分遠程加載表單時:

$(function(){
    $(".listing").html("<%= escape_javascript(render 'matches/a_cool_form') %>");
});

新加載的表單沒有來自default_form_method的綁定。 過去我通過在js.erb中再次調用方法來解決此問題,如下所示:

 $(function(){
        $(".listing").html("<%= escape_javascript(render 'matches/a_cool_form') %>");
default_form_method();
    });

但這似乎是多余的,我想知道(?)它是否會降低性能。

使資產管道方法始終綁定(即使在客戶端加載表單時)的解決方案是什么? 我假設它與最后加載函數有關。

這是因為bind將僅綁定到現有元素,而不是動態加載的元素。 您是否嘗試過on (替代live )?

function default_form_method(){
    $("form[data-remote='true']").on("ajax:error", function(evt, xhr, status, error){
        //show the errors, etc.
    })
    .on('ajax:success', function(evt, data, status, xhr){
      // clear the form, etc.
    });
}

暫無
暫無

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

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