Closing Javascript - submitting a form starts before I talk about it

I tried to associate some simple logic with closing javascript / jquery in order to bind the form to jQuery validation. The normal code looks like this:

// attach the jquery unobtrusive validator
$.validator.unobtrusive.parse("#formName");

// bind the submit handler to unobtrusive validation.
$("#formName").data("validator").settings.submitHandler = function() {
    viewModel.Save( $("#formName" ) );
};

It works great. I just wanted to wrap it and make it cleaner. So I wrote this.

(function ($){
    $.fn.submitHandler = function(callback){
        var container = $(this);
        // attach the jquery unobtrusive validator
        $.validator.unobtrusive.parse(container);

        // bind the submit handler to unobtrusive validation.
        $(container).data("validator").settings.submitHandler = callback(container);
        return true;
    };
})(jQuery);

So the inevitable goal is that I could just do it in the future.

$("#formName").submitHandler(function (e) {
        viewModel.Save(e);
    });

I know this sounds silly, but I thought it was a good chance to learn more. I only recently learned about closing Javascript and wanted to try it, and it seemed like a good check.

, HTML- , , ... . -, "" , , , .

"" , , alert Save. APPEAR, -.

, .

<form id="_formName" action="" method="post">
    <input type="text" required="required" />
    <button type="submit">Submit</button>
</form>

<script type="text/javascript">
    var viewModel = {
        Save: function ($form) {
            alert($form.attr('id'));
        }
    };

    $("#_formName").submitHandler(function (e) {
        viewModel.Save(e);
    });

</script>
+3
1

, :

// bind the submit handler to unobtrusive validation.
$(container).data("validator").settings.submitHandler = callback(container);

"submitHandler"... , , " " "" "submitHandler"... , , .

( , , , ):

// bind the submit handler to unobtrusive validation.
$(container).data("validator").settings.submitHandler = function() { callback(container); };
+6

All Articles