Why use jQuery inline events

I'm just wondering if anyone can point out why you should use jQuery event bindings rather than native JavaScript. My colleague 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 the question arises as to why my code should be used, I could not indicate any specific reason, except for syntactic clarity and agreement. So are there any other reasons why the second example could be used compared to the first? If not, then what is the real advantage of using jQuery in this case?

+4
source share
3 answers

One reason is that you don’t have to worry about trampling previously defined event callbacks. jQuery will queue and run all of them.

Note. Your rewritten version will also attach the behavior to something on the page with the form class, while the original version is attached to the first form on the page, regardless of its class. Perhaps this is not what you want.

+3
source

The problem with the onsubmit event is that only one handler can be specified for each element and each event. In a normal browser, you can use addEventListener , but which IE? Thanks to jQuery, you can forget which browser works with your script and just add many listeners to one element.

Or from one to many, from many to many, or from one to one, as in the first example.

+2
source

A second example would be better if there are several forms in which you want to add submit functions. In addition, there is no technical reason to prefer the second over the first.

Consistency is a reasonably good reason for the second IMO. Experienced developers will process it either without thought, but a green talent can force itself to mentally shift gears.

+1
source

Source: https://habr.com/ru/post/1411206/


All Articles