Wednesday, May 6, 2009

Javascript Closures

A re-introduction to JavaScript and Simplify Scope with Javascript Closures have a good introduction on the concept of javascript closures. A closure is the combination of a function and the scope object in which it was created. Closures let you save state. The memory of a closure can be freed only when the returned callMe is no longer accessible.

function createClosure(scope_) {
    var origScope = scope_;

    var callMe = function() {   // inner private function
        origScope.somefunc();
    }
    return callMe;    // inner function returned
}

// preserve 'this'
someobject.someproperty = createClosure(this);

function makeAdder(a) {
    return function(b) {
        return a + b;
    }
}

x = makeAdder(5);  // each call to the outer function create a closure
y = makeAdder(20);

x(6)    // return 11, with scope object a=5, 
        // a closure preserves the arguments and variables in all scopes it contains. 
y(7)    // return 27, with scope object a=20

Any nested function forms closure. It doesn't have to be returned, it can be an anonymous inner function as below. We should try to avoid closure whenever possible, it may potentially cause memory leak if there exists circular reference between JS object and DOM object.
function assignOnclick(element) {
   element.onclick = function() {
      this.style.backgroundColor = 'blue';
   };
}

See: Functions and function scope

Tuesday, May 5, 2009

Rounded Box



<div class="boxcontainer">
<div class="t"><div class="b"><div class="l"><div class="r">
<div class="bl"><div class="br"><div class="tl"><div class="tr">
<div class="boxlabel">{LABEL}</div>
<div class="boxcontent">{CONTENT}</div>
</div></div></div></div>
</div></div></div></div>
</div>


.t {background: url(/images/dot.jpg) 0 0 repeat-x;}
.b {background: url(/images/dot.jpg) 0 100% repeat-x;}
.l {background: url(/images/dot.jpg) 0 0 repeat-y;}
.r {background: url(/images/dot.jpg) 100% 0 repeat-y;}
.bl {background: url(/images/bl.jpg) 0 100% no-repeat;}
.br {background: url(/images/br.jpg) 100% 100% no-repeat;}
.tl {background: url(/images/tl.jpg) 0 0 no-repeat;}
.tr {background: url(/images/tr.jpg) 100% 0 no-repeat; padding: 5px;}

.boxlabel {
float:left;
display:inline;
position:relative;
top:-5px;
left:5px;
padding: 0px 2px 0px 2px;
background-color:#FFFFFF;
color:#1E90FF;
font-size:10;
font-family: Arial;
}

.boxcontent {
position:relative;
top:-5px;
text-align: left;
}

.boxcontainer {
margin: 5px;
}

The boxlabel float left with relative/top/left position to adjust its position. And its background-color is set to make the background opaque, otherwise, it is transparent and the below border line is shown.

Also, note that we have a padding on the last img div, to avoid text inside the box overlap with image.

See: CSS and Round Corners: Build Boxes with Curves