简体   繁体   English

如何干燥Rails / AJAX / Bootstrap 3模态错误处理?

[英]How can I DRY up my Rails/AJAX/Bootstrap 3 Modal Error Handling?

I have a series of Controllers in my Rails application that are all rendering a create.js.erb file upon successful AJAX submission via a Bootstrap 3 Modal input. 我的Rails应用程序中有一系列Controller,它们通过Bootstrap 3 Modal输入成功提交AJAX后,都会呈现一个create.js.erb文件。 I've also followed this description here to add error handling - so when the server returns an unprocessable entity the errors for each modal are rendered in a <span></span> help block. 我在这里也按照此说明添加了错误处理-因此,当服务器返回不可处理的实体时,每个模式的错误都会在<span></span>帮助块中呈现。 All of this works perfectly. 所有这些完美地工作。

My issue is that the code doesn't seem very DRY. 我的问题是代码看起来不太干。 Every new Modal I add to the app (I'm up to 7 now) requires that I target it in the Jquery/AJAXerror handling (in the way that I'm using it) - see the code below: 我添加到应用程序的每个新Modal(现在我最多7个)都要求我将其定位为Jquery / AJAXerror处理(以我使用它的方式)-请参见以下代码:

$(document).ready(function(){

  $(document).bind('ajaxError', 'form#new_person', function(event, jqxhr, settings, exception){

// note: jqxhr.responseJSON undefined, parsing responseText instead
$(event.data).render_form_errors( $.parseJSON(jqxhr.responseText) );

  });

});

The relevant part is $(document).bind('ajaxError', 'form#new_person', function(event, jqxhr, settings, exception){ 相关部分是$(document).bind('ajaxError', 'form#new_person', function(event, jqxhr, settings, exception){

This is targeting the form#new_person , and I have one of each for every form in my app. 这是针对form#new_person ,我的应用程序中每种表单都有一个。 It works fine but seems very unnecessary to repeat myself this much, when all I'm changing in each block of code is the selector. 它工作正常,但是当我在每个代码块中更改的只是选择器时,似乎不需要重复这么多。

Is there a method I can add to this where I can add each of my selectors as a list, or somehow tell the Jquery to only fire the AJAXerror call once? 有没有可以添加到列表中的选择器的方法,或者以某种方式告诉Jquery仅触发一次AJAXerror调用?

You can use comma separated group selector like this: 您可以使用逗号分隔的组选择器,如下所示:

$(document).bind('ajaxError', 'form#new_person, sel#f2, sel#f3, sel#f4',  
                                        function(event, jqxhr, settings, exception){

or make a var selectors like: 或制作类似var选择器

var selectors = 'form#new_person, sel#f2, sel#f3, sel#f4';
$(document).bind('ajaxError', selectors, function(event, jqxhr, settings, exception){
//------------use it here-----^---^---^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM