简体   繁体   中英

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. 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. 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:

$(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){

This is targeting the form#new_person , and I have one of each for every form in my app. 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?

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 selectors = 'form#new_person, sel#f2, sel#f3, sel#f4';
$(document).bind('ajaxError', selectors, function(event, jqxhr, settings, exception){
//------------use it here-----^---^---^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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