V
V
vadim_tur2015-11-05 11:10:25
JavaScript
vadim_tur, 2015-11-05 11:10:25

Best practice: what is the best way to subscribe to events?

I use OOP and jquery to subscribe to events, in VK files I noticed that the subscription to events occurs in html using onclick, onmousedown, etc. So there was a vprobros, how best to subscribe? What are the + and - of these methods?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin Kitmanov, 2015-11-05
@vadim_tur

Subscribing to events via HTML element attributes is bad in two ways:
1) It mixes markup and behavior. This means that in order to figure out what is happening, you need to alternately look into *.html and *.js, there are more chances to break something inadvertently or make a stupid mistake like a typo.
2) You can't hang more than one handler through an attribute.
However, with all of the above, it can be convenient if the code is extremely small. If your entire page consists of a calculator with three fields and two buttons, it makes no sense to include a framework there and fanatically follow all the best practices.

I noticed in VK files
The developers of VK, despite the incredible promotion of the service, are ordinary assholes, at least in terms of the front-end.

D
Denis Ineshin, 2015-11-05
@IonDen

$('.element').on('eventName', function () {...}); // обычная подписка
$(document).on('eventName', '.element', function () {...}); // делегирование событий

V
Vitaly Inchin ☢, 2015-11-05
@In4in

The only thing I try to sign via HTML is the magic return false, and only because of the difficulty with IE ( event.returnValue/preventDefaullt, as well as e||event).
I don’t see the point in hanging something else, it’s very inconvenient. Starting from that. that no context is passed to the function, ending with a limit of only 1 handler. In addition, you will either have to score window, creating many functions in the global scope, or shove all the handlers into one object as methods and complicate your life. But still, the main inconvenience is that in which case you have to run to HTML to see what a certain function does, and if its different parts are also divided into files...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question