I was attempt to wrap some simple logic into a javascript/jquery closure to bind a form to jQuery validate. 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" ) );
};
Works wonderfully. 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 inevitible goal is that I could just do this in the future.
$("#formName").submitHandler(function (e) {
viewModel.Save(e);
});
I know it seems silly, but I thought it was a good chance to learn more. I just recently learned about Javascript closures and wanted to try it out, and this felt like a good thing to test it on.
The problem is, if I make an HTML form and try to bind this to it, it does work like I want…but it works twice. First, the form just ‘posts’ when the page loads, then it does the behavior I want and expect after that.
Edit
When I say the form ‘posts’, I mean that the alert dialog in the Save function fires. There does not APPEAR to be any server-post back.
Here is the form I am using to test it on.
<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>
I believe your problem is with this line:
Here you are intending to assign a function reference to the “submitHandler” property… but, what you are actually doing, is calling the function “callback” with a parameter “container”, and assigning the result of that evaluated expression to the “submitHandler” property… which, I don’t believe you were intending to do.
You might try this instead (keep in mind, I really don’t know the specifics of your situation, i’m just going off what I can deduce):