Reputation: 47169
I'm just wondering if someone could point out why one should use jQuery event bindings rather then native JavaScript. A colleague of mine sent me the following code.
document.forms[0].onsubmit = function () {
if (Page_IsValid) {
$("#dialog").dialog({
height: 140,
modal: true,
resizable: false,
title: ''
});
$(".ui-dialog-titlebar").hide();
}
}
And I told him to rewrite it as.
$(".form").submit(function () {
if (Page_IsValid) {
$(".dialog").dialog({
height: 140,
modal: true,
resizable: false,
title: '',
open: function (event, ui) {
$(".ui-dialog-titlebar").hide();
}
});
}
});
But when queried about why one should use my code I couldnt provide any specific reason other than syntactic clarity and convention. So are there any other reasons one would use the second example over the first? If not, what is the real advantage of using jQuery in this case?
Upvotes: 4
Views: 285
Reputation: 3465
The problem with onsubmit
event is that only one handler can be set per element and per event. In normal browser you can use addEventListener
but what IE? Thanks to jQuery you can forget what browser running your script and just add many listeners to one element.
Or one to many, many to many or just one to one like in your first sample.
Upvotes: 2
Reputation: 7451
The second example will do better if there are multiple forms you want add submit functions to. Apart from that there is no technical reason to prefer the second over the former.
Consistency is a good enough reason for the second IMO. Seasoned developers will process either without thought, but green talent may find themselves having to mentally shift gears.
Upvotes: 1
Reputation: 19485
One reason is you don't have to worry about trampling over previously-defined event callbacks. jQuery will queue them up and run all of them.
note: Your rewritten version will also attach the behavior to anything on the page with a class of form
, while the original version attaches to the first form on the page, regardless of its class. This may not be what you want.
Upvotes: 3