Friday, April 29, 2011

What is Unobtrusive JavaScript?

If we look at the dictionary, the word obtrusive means "having or showing a disposition to obtrude, as by imposing onself or one's opinions on others". The synonyms are as interfering, meddlesome, etc.


Hence, unobtrusive is just the opposite of obtrusive i.e non interfering or meddlesome.
Unobtrusive Javascript as it suggest just means non-interfering or non-meddlesome javascript.

If we are able to remove the javascript from the source document and place it in an external file, then we are alomost there to say we have achieved unobtrusive javascript. The reason we stressed almost there is because "unobtrusive javascript" is a technique where we separate the behaviour layer from the presentation layer.




Monday, April 25, 2011

Javascript : Closer look at closure

Closure as defined in "Javascript closures for dummies" :
  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

Javascript : Self-invoking functions : function() { } ();

A self invoking function is one that's invoked as soon as it's declared.
They are they run immediately upon read by the browser.

Understanding this concept will help you to understand closure in javascript.

[code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        }
 [code : html]
<input type="button" value="click me" onclick="obj.pub_func();" />

If you run the above example you will probably receive an error message like " Object doesn't support property or method 'pub_func'". The reason being the object is not created yet.

Well, we have a solution to this problem in javascript in the form of "self invoking function". We will need to get the browser invoke it as soon as it is definded by insert "( );" at the end of the function.


 [code : javascript ]
 var obj = function () {
            var private1 = 1;
            var private2 = 2;

            var priv_func = function () {
                alert(private1);
            }

            return {
                public1: 'one',
                public2: 'two',

                pub_func: function () {
                    alert(this.public1);
                    alert(private2);
                }
            };

        } ();