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:
$.validator.unobtrusive.parse("#formName");
$("#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);
$.validator.unobtrusive.parse(container);
$(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>