Event Delegation: Save thou webpage

To make a web page interactive web developers rely on Events on the page. Event handling could be as easy as reloading the page on click of a button or as complex as following mouse pointer and responding to it. The usual way to do this is onEvent do some thing.

<button name="aButton" id="aButton" onclick="alert('Hello World!')">Cliché</button>


There are so many ways to handle events and then do something. Inline, shown above, unobtrusive, shown below.

<button name="anotherButton" id="anotherButton">Another Cliché</button>
document.getElementById('anotherButton').addEventListener('click', function(){alert('Hello World!')}, false);

One can add as many as event listeners required for an event occurring for an element. Well, not really a wise idea. Think of Gmail inbox set to display 100 emails in a row. Does that mean100 addEventListener? Not a good idea. Here comes a very simple technique called Event Delegation. Example

<ol id="olElem">
 <li id="li1">One</li>
 <li id="li2">Two</li>
 <li id="li3">Three</li>
 <li id="li4">Four</li>
 <li id="li5">Five</li>
 <li id="li6">Six</li>
 <li id="li7">Seven</li>
 <li id="li8">Eight</li>
 <li id="li9">Nine</li>
 <li id="lin">n</li>
document.getElementById('olElem').onclick = function(e){
 e = e || window.event;
 var target = e.target || e.srcElement;
 var textClicked = document.getElementById(target.id).innerHTML;
 alert('You clicked ' + textClicked);

This is all due to Event Bubbling which simply means that an event bubbles up to document root. So, when I click on “Nine”, the element li9 tells its parent that it got clicked, which in turn informs its parent and so on.

Method chaining

I love the way CodeIgniter explains method chaining by saying.

Method chaining allows you to simplify your syntax by connecting multiple functions.

As explained above it simply lets you do things like

FileObject->OpenFile('FileName')->AppendLine('Hello World!')->CloseFile()

Its neat. But in PHP, you have to have PHP5.x. This wonderful thing is also available in JavaScript. From jQuery home page


How to do method chaining?
To have an object chain methods every method in that object must return a reference to itself. Easy. Example?

class MethodChainingExample{
	public function methodOne(){
		echo __METHOD__." \n";
		return $this;
	public function anotherMethod(){
		echo __METHOD__." \n";
		return $this;
	public function oneMoreMethod(){
		echo __METHOD__." \n";
		return $this;
$example =  new MethodChainingExample;