繁体   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