How can I correctly capture and re-fire the form submit event, guaranteed?

前端 未结 4 1052
名媛妹妹
名媛妹妹 2021-02-07 03:23

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 jQu

相关标签:
4条回答
  • 2021-02-07 03:32

    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.
    0 讨论(0)
  • 2021-02-07 03:33

    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
        }
    });
    
    0 讨论(0)
  • 2021-02-07 03:44

    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.

    0 讨论(0)
  • 2021-02-07 03:45

    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);
    
    0 讨论(0)
提交回复
热议问题