简体   繁体   English

如何确保在控制器特定的JS之后调用Rails资产管道中的JQuery脚本?

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

For instance: 例如:

I have a general form error handling script which runs as follows: 我有一个通用的表单错误处理脚本,其运行方式如下:

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.

    });
}

Now when I load a form remotely, via a partial such as index.js.erb: 现在,当我通过诸如index.js.erb之类的部分远程加载表单时:

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

The newly loaded form does not have the binding from default_form_method. 新加载的表单没有来自default_form_method的绑定。 In the past I've fixed this by calling the method again in js.erb as follows: 过去我通过在js.erb中再次调用方法来解决此问题,如下所示:

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

But that seems redundant and I wonder (?) if it slows down performance. 但这似乎是多余的,我想知道(?)它是否会降低性能。

What's the solution to get the asset pipeline methods to always bind, even when a form is loaded client-side? 使资产管道方法始终绑定(即使在客户端加载表单时)的解决方案是什么? I'm assuming it has to do with loading the function last. 我假设它与最后加载函数有关。

That's because bind will only bind to existing elements, not dynamically loaded elements. 这是因为bind将仅绑定到现有元素,而不是动态加载的元素。 Have you tried on (replacement for live )? 您是否尝试过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.

相关问题 如何在Rails资产管道中使用我的Jquery插件? - How do I use my Jquery plugin in the Rails asset pipeline? Rails资产管道如何链接到生产中的特定.js文件 - Rails asset pipeline how to link to a specific .js file on production 如何从Rails资产管道中的不同文件调用JS函数 - How do I call a JS function from a different file in the Rails asset pipeline 无法在Rails(5+)中加载控制器特定的javascript文件 - Unable to load controller-specific javascript file in Rails (5+) 如何在Rails中输出整个资产管道? - How do I output the entire asset pipeline in rails? JS进入Rails Asset Pipeline - JS into Rails Asset Pipeline Rails 4 / Sprockets:特定于控制器的JavaScript随处可用? - Rails 4 / Sprockets: controller-specific JavaScripts are available everywhere? 如何在文档头中使用AngularJS控制器特定的作用域值? - How can I use AngularJS controller-specific scope values in document head? 如何确保在调用js函数之前将动态生成的div加载到DOM中? - How do I make sure dynamically generated div is loaded into DOM before js function is called on it? 将Adobe Edge脚本添加到Rails资产管道中 - Adding Adobe Edge Scripts into Rails Asset Pipeline
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM