How can I correctly capture and re-fire the form s

2020-05-30 09:14发布

问题:

This is probably not your usual "How do I capture form submit events?" question.

I'm trying to understand precisely how form submit events are handled by jQuery, vanilla Javascript, and the browser (IE/FF/Chrome/Safari/Opera) -- and the relationships between them. (See my other question.) After hours of Googling and experimenting, I still cannot come to a conclusion, either because of discord or vagueness.

I'm finishing up a script which integrates with website forms so that the forms can't be submitted until an AJAX request comes back.

Ideally:

  1. User fills out form
  2. Form is submitted -- but no previously-bound event handlers are called, except mine
  3. My handler makes an API request (asynchronously, of course)
  4. User confirms validation results from API response
  5. Form submit continues normally, automatically, invoking the other handlers which before were suppressed

My current understanding is that: (these may be wrong, please correct me if so)

  • jQuery binds form submit event handlers to the submit button click events
  • Event handlers directly on the submit element click events (whether in the markup like onclick="" or bound using jQuery) are executed first
  • Event handlers on the form submit events (whether in the markup like onsubmit="" or bound using jQuery) are executed next
  • Calling $('[type=submit]').click() doesn't invoke the form's submit event, so its handlers don't get called
  • Calling $('form').submit() doesn't invoke the submit button's click event, so its handlers don't get called
  • Yet somehow, a user that clicks the submit button ends up invoking handlers bound to the form's submit event... (but as mentioned above, invoking click on the submit button doesn't do the same)
  • In fact, any way the user submits the form (via submit button or hitting Enter), handlers bound with jQuery to the form submit event are called...

Right now, I am:

  1. Unbinding handlers bound with jQuery to the submit button's click event while preserving a reference to them
  2. Binding my own handler to the submit button's click event, so it executes first
  3. Taking any handlers bound in the markup using onclick="" and onsubmit="" (on their respective elements) and re-binding them using jQuery (so they execute after mine), then setting the attributes to null
  4. Re-binding their handlers (from step 1) so they execute last

Actually, this has been remarkably effective in my own testing, so that my event handler fires first (essential).

The problem, and my questions:

My handler fires first, just as expected (so far). The problem is that my handler is asynchronous, so I have to suppress (preventDefault/stopPropagation/etc) the form submit or submit button click event which invoked it... until the API request is done. Then, when the API request comes back, and everything is A-OK, I need to re-invoke the form submit automatically. But because of my observations above, how do I make sure all the event handlers are fired as if it were a natural form submit?

What is the cleanest way to grab all their event handlers, put mine first, then re-invoke the form submit so that everything is called in its proper order?

And what's the difference, if any, between $('form').submit() and $('form')[0].submit()? (And the same for $('[type=submit]').click() and $('[type=submit]')[0].click())

tl;dr, What is the canonical, clear, one-size-fits-all documentation about Javascript/jQuery/browser form-submit-event-handling? (I'm not looking for book recommendations.)


Some explanation: I'm trying to compensate for a lot of the Javascript in shopping cart checkout pages, where sometimes the form is submitted only when the user CLICKS the BUTTON (not a submit button) at the bottom of the page, or there are other tricky scenarios. So far, it's been fairly successful, it's just re-invoking the submit that's really the problem.

回答1:

Bind to the form's submit handler with jQuery and prevent the default action, then, when you want to submit the form, trigger it directly on the form node.

$("#formid").submit(function(e){
    // prevent submit
    e.preventDefault();

    // validate and do whatever else


    // ...


    // Now when you want to submit the form and bypass the jQuery-bound event, use 
    $("#formid")[0].submit();
    // or this.submit(); if `this` is the form node.

});

By calling the submit method of the form node, the browser does the form submit without triggering jQuery's submit handler.



回答2:

These two functions might help you bind event handlers at the front of the jquery queue. You'll still need to strip inline event handlers (onclick, onsubmit) and re-bind them using jQuery.

// prepends an event handler to the callback queue
$.fn.bindBefore = function(type, fn) {

    type = type.split(/\s+/);

    this.each(function() {
        var len = type.length;
        while( len-- ) {
            $(this).bind(type[len], fn);

            var evt = $.data(this, 'events')[type[len]];
            evt.splice(0, 0, evt.pop());
        }
    });
};

// prepends an event handler to the callback queue
// self-destructs after it's called the first time (see jQuery's .one())
$.fn.oneBefore = function(type, fn) {

    type = type.split(/\s+/);

    this.each(function() {
        var len = type.length;
        while( len-- ) {
            $(this).one(type[len], fn);

            var evt = $.data(this, 'events')[type[len]];
            evt.splice(0, 0, evt.pop());
        }
    });
};

Bind the submit handler that performs the ajax call:

$form.bindBefore('submit', function(event) {
    if (!$form.hasClass('allow-submit')) {
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();

        // perform your ajax call to validate/whatever
        var deferred = $.ajax(...);
        deferred.done(function() {
            $form.addClass('allow-submit');
        });

        return false;
    } else {
        // the submit event will proceed normally
    }
});

Bind a separate handler to block click events on [type="submit"] until you're ready:

$form.find('[type="submit"]').bindBefore('click', function(event) {
    if (!$form.hasClass('allow-submit')) {
        // block all handlers in this queue
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
        return false;
    } else {
        // the click event will proceed normally
    }
});


回答3:

There must be many ways to address this - here's one.

It keeps your ajax function (A) separate from all the others (B, C, D etc.), by placing only A in the standard "submit" queue and B, C, D etc. in a custom event queue. This avoids tricky machinations that are otherwise necessary to make B, C, D etc. dependent on A's asynchronous response.

$(function(){
    var formSubmitQueue = 'formSubmitQueue';

    //Here's a worker function that performs the ajax.
    //It's coded like this to reduce bulk in the main supervisor Handler A.
    //Make sure to return the jqXHR object that's returned by $.ajax().
    function myAjaxHandler() {
        return $.ajax({
            //various ajax options here
            success: function(data, textStatus, jqXHR) {
                //do whatever is necessary with the response here
            },
            error: function(jqXHR, textStatus, errorThrown) {
                //do whatever is necessary on ajax error here
            }
        });
    }

    //Now build a queue of other functions to be executed on ajax success.
    //These are just dummy functions involving a confirm(), which allows us to reject the master deferred passed into these handlers as a formal variable.
    $("#myForm").on(formSubmitQueue, function(e, def) {
        if(def.state() !== 'rejected') {
            if (!confirm('Handler B')) {
                def.reject();
            }
        }
    }).on(formSubmitQueue, function(e, def) {
        if(def.state() !== 'rejected') {
            if (!confirm('Handler C')) {
                def.reject();
            }
        }
    }).on(formSubmitQueue, function(e, def) {
        if(def.state() !== 'rejected') {
            if (!confirm('Handler D')) {
                def.reject();
            }
        }
    });

    $("#myForm").on('submit', function(e) {
        var $form = $(this);
        e.preventDefault();
        alert('Handler A');
        myAjaxHandler().done(function() {
            //alert('ajax success');
            var def = $.Deferred().done(function() {
                $form.get(0).submit();
            }).fail(function() {
                alert('A handler in the custom queue suppressed form submission');
            });
            //add extra custom handler to resolve the Deferred.
            $form.off(formSubmitQueue+'.last').on(formSubmitQueue+'.last', function(e, def) {
                def.resolve();
            });
            $form.trigger(formSubmitQueue, def);
        }).fail(function() {
            //alert('ajax failed');
        });
    });
});

DEMO (with simulated ajax)

As an added bonus, any of the handlers in the custom queue can be made to suppress any/all following handlers, and/or suppress form submission. Just choose the appropriate pattern depending on what's required :

Pattern 1:

Performs its actions only if all preceding handlers have not rejected def. and can suppress all following handlers of Pattern 1 and Pattern 2.

$("#myForm").on(formSubmitQueue, function(e, def) {
    if(def.state() !== 'rejected') {
        //actions as required here
        if (expression) {
            def.reject();
        }
    }
});

Pattern 2:

Performs its actions only if all preceding handlers have not rejected def. but does not suppress following handlers.

$("#myForm").on(formSubmitQueue, function(e, def) {
    if(def.state() !== 'rejected') {
        //actions as required here
    }
});

Pattern 3:

Performs its actions unconditionally but can still suppresses all following handlers of Pattern 1 and Pattern 2.

$("#myForm").on(formSubmitQueue, function(e, def) {
    //actions as required here
    if (expression) {
        def.reject();
    }
});

Pattern 4:

Performs its actions unconditionally, and does not suppress following handlers.

$("#myForm").on(formSubmitQueue, function(e, def) {
    //actions as required here
});

Notes:

  • The deferred could be resolved in these handlers in order to submit the form immediately without processing the rest of the queue. But in general, the deferred will be resolved by the '.last' handler added to the queue dynamically before the queue is triggered (back in Handler A).
  • In the Demo, all the handlers are of Pattern 1.


回答4:

Here's how I ended up doing this, and it has been very successful so far in numerous test cases. I learned an awful lot about events, particularly form submit events, in relation to jQuery. I don't have time to post a comprehensive encyclopedia of all the information I collected, but this will suffice for now:

This was for the SmartyStreets LiveAddress API jQuery Plugin which validates addresses before the user leaves the page.

The most successful method was by grabbing the submit button's click event. The snippet below is found in the jquery.liveaddress.js file. It gets references to as many event handlers as possible (jQuery, onclick --- the onclick ones fire first), uproots them, plops down its own (submitHandler), and layers the others on top of it. It's worked successfully on sites like TortugaRumCakes.com (checkout) and MedicalCareAlert.com (homepage and checkout) as well as many others.

The full code is on GitHub. This particular segment goes for the "click" on the submit button, but similar code is used to handle form submit also. jQuery's submit() function seems to be rather proprietary... but this handling both ensures it gets called even when .submit() is called programmatically on a jQuery object.

var oldHandlers, eventsRef = $._data(this, 'events');

// If there are previously-bound-event-handlers (from jQuery), get those.
if (eventsRef && eventsRef.click && eventsRef.click.length > 0)
{
    // Get a reference to the old handlers previously bound by jQuery
    oldHandlers = $.extend(true, [], eventsRef.click);
}

// Unbind them...
$(this).unbind('click');

// ... then bind ours first ...
$(this).click({ form: f, invoke: this }, submitHandler);

// ... then bind theirs last:
// First bind their onclick="..." handles...
if (typeof this.onclick === 'function')
{
    var temp = this.onclick;
    this.onclick = null;
    $(this).click(temp);
}

// ... then finish up with their old jQuery handles.
if (oldHandlers)
    for (var j = 0; j < oldHandlers.length; j++)
        $(this).click(oldHandlers[j].data, oldHandlers[j].handler);