I have been reading about some good practices in JavaScript and one of them was Unobtrusive JavaScript. The first point caught my attention
Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
On the wiki page, one of the examples is that you should bind actions to events in JS files instead of in the HTML. This example
<input type="text" name="date" id="date" />
...
window.onload = function() {
document.getElementById('date').onchange = validateDate;
};
is favored over
<input type="text" name="date" onchange="validateDate()" />
However, I would say I'd prefer the second code with onchange
attribute over the first one. My reasons for this are
- It is easily readable and immediately clear what will happen on change (or any other event) on that element.
- I don't have to got through JavaScript files and look where (and whether) the
onchange
event is bind and whether there are some other events such asclick
defined for#date
. - Frameworks such as AngularJS have
ng-click
and is mixing up HTML structure with JS. Why shouldn't I?
The disadvantages of not using unobtrusive javascript that I have read about are
- Polluting global namespace.
- Creating long and unreadable inline code.
- If the code for an event changes, you have to change it only in one place - that is in a JS file.
But I think that the disadvantages can be solved.
- Instead of polluting namespace, create the app in one variable so the code would look like
onchange="app.validateDate()"
and no polluting would happen. - Inline code would not be written and would be separated in a function in JS file, then it'd be called like
onclick="app.action();"
. - Isn't it the same as using a function in
onclick
attribute? Because in the end you have to make a change just in one function in both approaches whether it is$('input').change(function () {/* ... change ... */});
orapp.action = function () {/* ... change ... */}
.
So is it actually still considered a good practice?