3 ms·
Why not just: document.addEventListener('submit', ev => { if (ev.target is a kind of a form I want json submit on) { ev.preventDefault(
by megous 5y ago
Why not just:
document.addEventListener('submit', ev => {
if (ev.target is a kind of a form I want json submit on) {
ev.preventDefault();
handle_json_submit(ev.target)
}
}, true);
Instead of sprinkling onsubmit="..." everywhere.
- lolinder 5y agoThis comment has a good explanation: https://news.ycombinator.com/item?id=31173042 https://news.ycombinator.com/item?id=31173042 For myself, the biggest thing is locality. Coming into a large codebase that's been around for a while, it's a lot easier to understand if the event handlers are defined inline, right there with the form itself. If they aren't, you first have to determine experimentally that it's not using the default form behavior. Then you end up having to hunt down where in the code someone put the `addEventListener` calls and then read them to decide which calls (and which conditional branches) apply to this form. If the event handlers are instead defined on the forms themselves, the onsubmit behavior is immediately obvious just by looking at the form. It's a bit more code to write, but it's much easier to digest later.
- megous 5y ago> This comment has a good explanation: https://news.ycombinator.com/item?id=31173042 https://news.ycombinator.com/item?id=31173042 Not really..., neither memory leaks, nor missing the addition of event handling to newly added DOM elements is a problem for the addEventListener solution. If the codebase is using JSON submitted forms almost everywhere, it's easier to build that feature more declaratively, by adding support for a special enctype attribute value (using one global addEventListener that would handle it), for example: <form enctype="application/json"> ... That would be more in line with how other features of the <form> element work. addEventListener solution is also better if you decide to add CSP in the future.