Wednesday, February 27, 2008

Unobtrusive JavaScript

While serving the internet looking for something, i found someone talking about something called 'Unobtrusive JavaScript', it was the first time for me to hear that expression so i looked for it and found that

Unobtrusive JavaScript is one of the emerged paradigms in JavaScript, its main idea is to achieve more separation while working on web applications

Since now, we almost reached to an agreement to separate presentation from content/structure through separation of CSS from HTML, this paradigm is greedy and wants extra separation of behaviour from structure

lets look at this example to clarify things out
<#input type="text" id="date" onchange="validateDate(this);" />

here we can see that our structure is that simple input field but it is mixed by this onchange function which shows to us what this input does on change

Now, look at that one
<#input type="text" id="date" />

here we have only structure and no behaviour, so WHERE SHOULD WE ADD OUR BEHAVIOUR?, we should do that with javascript away from our presentation as follows

window.onload = function(){ //Wait for the page to load.
var input = document.getElementById('input');
input.onchange = function(){
//Do something changed.

This is the simplest illustration that i can give to this paradigm, it makes you live in a world of layers (structure, presentation, behaviour)

actually, i am admired with this paradigm so much because it layered our application and thus allowed for better separation but i think one of its problems is that looking at structure won't give you a quick idea about what elements behave until you visit the behaviour layer

finally, i would like to end with this nice quote from one of the articles i read about this topic
The first rule of the unobtrusive Javascript club is don't talk about the unobtrusive Javascript club.

this post isn't done yet until i hear from you what do you think about this emerged paradigm and whether it should be the dominant in the following years or not

No comments: