Wednesday, July 11, 2007

Handling multiple events in Javascript

This is perhaps going to be my first initiative to write a technical post, the effort mainly driven by my long hours of pondering over a problem that I faced earlier today. It was then that I decided that it is definitely not worth having anybody spend their valuable time trying to figure this out by themselves.I know that my usual reader's would find this a bit out of place, but I hope that they wouldn't mind this....

Events are one of the most frequently used features in the world of Javascript. They provide you with the ability to capture many user events that can help in designing more intuitive and user friendly interaction with any application. Some of the events that we might want to capture could be keystorkes, mouse clicks, mouse movements, etc.. All that we need to do to achieve this is to register the event-handler with the browser. On occurance of the event, the browser will call the corresponding event handler. This event handler can contain any logic built into it depending on the event that triggered it. Okay.. that should give you the sufficient overview of what you can achieve by using events. So lets get going with an example.

The most common and traditional method of attaching events with elements in a web page is as shown below.

elt.onClick = handler();
elt.onFocus = handler();

whereas the newer methods of using events and handlers are as shown below

document.addEventListener('',event_handler,false);
document.removeEventListener('',event_handler,false);

function_handler()
{
//do something here....
}

where event could be a 'click', 'keypress'

The race for winning the web-war between the two giants Netscape and Microsoft has had its impact on their way of handling events too. The above method is the one used by Netscape to register events. Whereas Microsoft uses the format shown below.

element1.attachEvent('onClick',event_handler1)
element2.attachEvent('onClick',event_handler2)


To detach an listener is equally easy..,

element1.detachEvent('onClick',event_handler2)

If you are unsure of the browser then you might want to use something like this..

function addEvent (elt, eventType, handler, captureMode){
if(docuement.addEventListener){
elt.addEventListener(eventType,handler,captureMode)
}
else{
elt.attachEvent('on'+eventType,handler);
}
}

Okay.. If you had observed the above example carefully, you might be wondering how this would work with multiple elements being registered for the same event. That's where the borwsers are smart. They keep track of the various handlers registered for that particular event, and they notify them all. But hey.., hold on, it ain't so simple.. you never know in which order the events are notified to the handlers. IN earlier versions it was not even possible to determine the order in which the handlers will get triggered. This can cause a lot of confusion when we have multiple handlers with the same target.

Now that we are familiar with the basics of handling events let get into the intricacies. Say for example that we have two elements e1 and e2 where e2 is deeper in the hierarchy. Both these are registered for the same event say 'keyDown'. Now when the event transpires, what order do the listeners follow in calling the corresponding handlers. Again, the titans opted for varying solutions and w3c ended up on a median. Nestcape said that the event should proceed from e1 to e2 (called as event Capturing), whereas Microsoft went for the opposite. Event proceeds from e2 to e1 which is called as 'Bubbling'. This is what we specified as the fourth parameter 'captureMode' in our addEvent() function earlier. Now w3c had to take a middle course by adoption both these models. For this purpose, we have a capturing phase and a bubbling phase.

e1.addEventListener('keyDown',handler1,false)
e2.addEventListener('keyDown',handler2,false)


where 'false' indicates a bubbling mode.

When the event on e2 is triggered, it starts off in the capturing mode where in it checks if the ancestor has any listeners in the capturing mode. Finding none, it will proceed to call handler2 and the bubbling mode starts off then. During the bubbling mode it will accordingly call the handler1 and traverses further till the top of the DOM is reached. Now consider the other case,

e1.addEventListener('keyDown',handler1,true)
e2.addEventListener('keyDown',handler2,false)


As usual it begins in the capturing mode on e2, and finding that the ancestor of e2 ie., e1 is in the capturing mode executes the handler1 before moving on to the handler2. Now if there were an element e0 which is the ancestor of e1 in the bubbling mode with handler0 then hanler0() would be the last to be called in the bubbling phase. Thus providing a feature to attach each listener with their own mode, it provides micro-control the order in which handlers should be called.

Now the next natural question is can we stop this bubbling ? The answer is yes..imagine a scenario where e2's handler should determine whether e1 should receive the event at all. We can stop the event from bubbling by event.cancelBubble = true which would prevent the next handler in the hierarchy from receiving the event. This could prove to be useful feature when the DOM is rich and you would want to stop the event from propagating up to the top of the hierarchy when there are no events attached to any of them. Please note that this is the method used by Microsoft. w3c suggests another implementation to do exactly the same

e1.stopPropagation();

so what do we do to ensure cross browser compatibility..? Its the plain old way of doing it..

function stopEvents(event){

if(event.stopPropagation){
event.stopPropagation();
}
else {
event.cancelBubble;
}
}


So are there any pitfalls here..? yes .. A couple of things that I can think of. Please do correct me if I am wrong.

There is no way of determining whether event handlers are registered to an element (in older implementations elt.onclick() would give you the handlers registered with it). So if we want to ensure that there are no other eventhandlers to an element we should probably use elt.removeEventListener(). Another issue that I faced was that the propagation in the capturing phase cannot be stopped. The only way to control could be in the bubbling phase, so one should be using the mode pretty carefully depending on the design. One other problem that I came across was something like this...

e1.addEventListener('click',handle1,true)
e2.addEventListener('click',handle1,true)


So now I had to determine what was the originator of the event. The solution was pretty simple, use the 'this' operator to determine the source. Recently I also realised that w3c had another variable dedicated for the purpose called 'currentTarget' which contains the reference of the element. But then I found this to work only with MOZ and not with IE. Perhaps IE doesnt have a 'currentTarget' implementation. However make a note that the 'srcElement' or 'target' would still be pointing to the initial element where the event originated.

And now if you might have any doubts, suggestions or clarifications, please post them as comments and I would be more than pleased to have a look at it.

Monday, July 09, 2007

Wimbledon '07.. clash of titans


"Yeah..." shouted Federer when he won a net point. That's something the media tapes should preserve like a treasure, for one doesn't hear those words coming out of Federer very often. Wimbledon 2007 has been a dull event so far with just a few sparks flying in the Federer-Fererro clash. Federer was definitely the one expected to win the title hands down. He did that but definitely not hands down as people would have imagined it. Things looked ominous when the match started and Federer raced to a 3-0 lead within 11 minutes of the start of the game. Nadal had barely warmed up when Federer was looking threateningly dangerous to breeze away with the first set. But Rafa was not the one to bow down so early... He ploughed his way back into the game by winning the next three games to bring down the early advantage that Federer held. The first set was an absolute treatise to watch and every one who watched the match had their pennies' worth for it. Rafa matched Federer shot by shot, point by point. The tie breaker saw Federer having three set points but Rafa prised out a couple of blitzkreigs to extend the game before losing it 9-7.



Take nothing away from Federer, for he played at his very best to bring out an amazing array of aces (totaled to 24 if I am not wrong) and kept Nadal lurching for points. Nadal is definitely not a great net player but it amazed me to see Federer miss his net volleys too.. Both played excellent base game but were highly error prone when it came to net points. Federer's smooth and stylish backhands were suitably returned by Nadal's curvy forehand top spins and there were many a great rallies played in this fashion. Both played to their strengths and one could see glimpses of an epic match in the making. The king of grass faltered just one time in the 9th game of the second set which was all that Rafa needed to seal the second set 6-4. This was the seventh set that Federer lost in the 53 matches and 5 years of this tournament !

The genius in Federer was matched by the resilience of Rafa and each held serves dragging the third set into yet another tie break. Federer's aces helped him seal the set quite easily at 7-3. Things looked dark for Rafa but the inspired Spaniard took the challenge by its horns and pounded the King of grass in the Fourth set to a whopping 4-0 lead. This was the first time that one has seen Federer run to every corner of the court. Nadal stamped his brilliance by playing to his strengths, his forehand shops and top spins were impeccable and amazingly accurate. Fourth set was quite a contrast to the first three, Federer looked lost and even cursed a couple of times... it was Nadal all the way.. Rafa whoppled the set 6-2 bringing the game to a 5 setter epic.

Federer had not broken Nadal for eternity (save the second game of the match) while the spaniard had comfortably broken him more than thrice. The first three games saw them hold their serves and fight hard to earn every point. Then the world saw why Federer was called the 'King of grass'. He broke Nadal twice in the set while the spaniard failed to do the same when he had his chances. Federer would have had a run for his money if only Rafa had to manage to clinch at least one of the breaks. You cant expect Federer to be too benevolent to give a second chance ;-) he ruthlessly murdered the Nadal challenge in the final set to clinch the tile 6-2. The Swiss exulted with a rare outburst of emotion.. it was quite understandable....


Whatever be the result of the match, one thing is pretty evident.. these two are the rulers of modern day tennis be it grass or clay... They have simply discarded the others from either versions of the game. Federer said after the match that the title could have easily been Rafa's too. He wasnt made to prespire as much in any version of the game ever before. Such was the quality and strength of Nadal. It was a fitting end to the rain-hit wimbledon where two legends fought with valor for the title in the presence of all time greats like Becker and Borg. With the fifth straight wimbledon title safely tucked under his belt, can the King of grass rest easy..?? Well hardly, with the way he was made to run for the title this time he can hardly afford to put away the Spaniard's brilliance. Nadal's performance in this final had thrown in many questions to the tennis world... is this the end of the Federer era...? Well, time will tell....

Monday, June 25, 2007

Story time..

Dedicated to my reader's who have consistently pulled my leg into writing a story...

I could see nothing, feel nothing.., numbness was overtaking me.. I knew that these were the last few minutes of my eventful life. I had been very important throughout and for the first time I realized that even I could meet with such a disastrous end. People say that when you are about to die, your entire lifetime flashes before your inward eye.., yes.. I am seeing it now.

This part of my life... it is called 'Happiness'. I was born important, an entire family was awaiting my arrival with great anticipation. I was born in Mumbai to an educated middle-class family. As I have said before, I brought joy into the family with my arrival, I gave them an identity in the society, I gave them opportunity, I gave them the oxygen they desired.. I was like Christ - the saviour for them and I relished that feeling of master-hood. I was the newest member of the family and was easily the object of interest right from Mom and Dad to the eight year old kid. Dad got through with an MNC soon after my birth and from thereon I was believed to be the lucky charm for the entire family. I was happy, very happy, happiest as any one could ever imagine.

Dad never left me alone and used to take me to all places along with him. I had become an important part of his life. There was this one time when he went to Europe on a business trip and I was the only one to accompany him. Mom repeatedly reminded him to take good care of me and to ensure my safety in the foreign land. Airports are the worst place and the officials the worst people on the entire earth. I was stunned by the amount of security checks that I had to undergo. Dozens of uniform clad officials walked around checking and re-checking each passenger and his belongings. They took me away from dad into a room for a couple of minutes, and that was the first time in my life that I was separated from my family. Those two minutes were like ages to me, I was scrutinized by a high-ranking official first and then by his subordinate and then after their approval was stowed back to dad. Gosh..! those two minutes scared me to death. Little did I know that this was just a sample of what was about to come.This part of my life... it is called 'Running'.

Switzerland was called as the 'land of dreams' and it truly was. It was so cold there that dad had to wrap me up to keep me from freezing. But I have to admit that I enjoyed my stay in the swiss lands until this incident happened..a ruffian snatched me from my dad's hands. It took a dozen police officials three days and eleven hours to trace my path before I was safely in the hands of my dad. To prevent any such mis-occurrences Dad decided to masquerade me and that changed my life altogether. I began to look different, think different...I felt as if I was slowly losing the charm that I possessed.

It has been five months since I was back in Mumbai, my birth place, a place that was dear to me. Since dad decided to stick with India having had a troubled European experience, I mostly remained confined to the two bedroom flat at Andheri(E). My exposure with the outside world ranged from the 'Kyon ki saans bhi bahu thi' that mom watched to the occasional BBC that dad watched on weekends. I hardly had any opportunity to go out either except on rare occasions where Dad took me to the nearby foreign exchange firm. This part of my life...this is called 'Sedateness'. Oh..! did I forget to mention that I was still masqueraded ?? Actually that state remained till this moment....the last one, I knew, before I would be no more.

Then came the blackest day of my life and I didn't know what was in store for me when dad decided to take me to the consulate exactly seven hours and sixteen minutes before this moment. It was raining torrents in Mumbai and the roads were flooded blocking traffic and wreaking a havoc. Dad had me wrapped in a rain-proof outfit and we were on our way in his car. We were just one block away from the consulate when the wheel got stuck in a slush irretrievably. Dad was usually a very rational and logical person, but at that opportune moment, in his desperation to reach the consulate, he pulled me out of the car and ran out in the rain. Running was easier, as the traffic had almost been at a stand-still owing to the flooded roads. Then it happened...I felt a jolt as a motorist hit dad from the behind and dad let go of me
instinctively to prevent a face first fall. I am puny sized and was pulled in by the flood current into an open drainage. Curse the MC for not maintaining the drainage properly. The last word that I ever heard from dad was "Holy Shit!"..... I flew clear off the main course and landed splash on bunch of floating scum. This part of my life is called "THE END".

I lay there with the water seeping through the so called water-proof layer at a slow pace. I knew that my end was near. I was being choked slowly and steadily by the water which was immersing me as if in an ablution. I could feel the suffocation gripping on me as darkness enveloped me completely. I could sense the stench of the gutter, the filth that surrounded me. I began to realize that these were the very last moments of my life and how helpless I was.. that was two seconds ago from now. The present had something else in store for me...."DEATH".

A gentle wind whistled past me, the first rays of the morning sun shone upon me benignly. I was lying on my dad's bed, uncleaned and dry but comfortable nevertheless. I could see the entire family standing around me and dad was examining me thoroughly. Dad's expression changed from frantic to helpless...."Shit !!" he said flinging me out of the window. I lay there on the heap of scrap wondering what I had done to deserve this treatment. All that was left of me now was a blue cover with the golden embossed letters reading "Passport"...

Inspired by an untrue story :D
Mighty Titan.


"The crappiest piece of story we have ever heard."
-The Livingston post.


"So crappy that you cant wait to finish it."
-The Wastes of India.


"The worst story ever told in this universe."
-All times.

"Enna koduma saar idhu.."
-Mr.Saravanannnn...


Disclaimers: This story is not about me, did not happen to me and is a mere figment of my imagination. Any resemblance to a person living or dead is purely co-incidental..

Monday, May 28, 2007

Coffeee.. cafe.. kaaapeeee..


Java...? heck no...this post is dedicated not to mere mortals, but to the ones who truly savor the ambrosia, the mere fragrance of which can instigate life, the best (or is it not..?) beverage that man has ever discovered..'coffee'. For a substantial subset of people in the world, their days cannot kick-start without a cup of coffee. Oh no.. this is not going to be yet another of my 'incident-o-mania' posts. This is going to be an erudite conglomerate of facts and figures ! So my dear readers, please wear your scientific shoes before stepping on further.

Okay.. lets now get going with the composition of coffee. Most of us are familiar with the infamous ingredient called caffeine. It would surprise you to know that this is less than 1% of the components that make coffee. The major contents of coffee are

Polysaccharides - 12 %
Chlorogenic acids - 15% (mono/di esters of hydroxycinnamic acid)
phenolic polymers - 20%
quinic acid / quinides - 8%
caffeine - 1%
water - 4%
minerals and other organic acids - 40%

Most of these components are not the inherent innate components of coffee. They are the compounds that are formed during the various processes that it undergoes like
roasting, blending and brewing.

Now moving on to the well-known stimulating effect of coffee. The main reason for feeling fresh after a coffee is because of the quinides. The brewing process results in the isomerisation of these quinides which have varying effects on our brain. While some research indicate that the synergetic effects of these quinides on a biological entity are healthy, certain others indicate that such hyperactivity cannot be handled by the brain. However we cannot be certain of the effects/side-effects of coffee till date because we are still quite ignorant of the effects of the numerous chlorogenic acids and quinide isomers. What we are sure is that the stimulant effect is due to the reaction of these compounds with the opiate system of the brain.

What benefits does the coffee offer to you ..? well, It boosts endurance by delaying fatigue and it improves long-term memory (Good news eh..?). It may help prevent kidney stones and it relaxes lung spasms during an asthma episode. And as you may have discovered, it stimulates your gastrointestinal tract. Moving on to the bad elements of coffee... it contains carcinogens(Homework: find out what a carcinogen can do to you.) which when taken in large quantities can be harmful. But then., hey who cares !! Its definitely the most refreshing drink on earth ! Remember folks .. anything cna happen over a cuppa coffee.. anything.....

Monday, May 07, 2007

Go Spidey !

No way I am gonna miss the review for the most awaited movie of the year.. Spidey 3. Needless to emphasize, the excitement was in plenty... when I say that,believe me.. I mean that ! We had even booked tickets almost 4 days in advance. If seeing an action movie is what you define as thrilling, seeing it in imax is an out of the world experience altogether.The big screen simply gobbles you up. If you as me 'can you touch your heart and say that you have ever followed an entire movie without missing every spoken word ?' I would today say.. "Yes..". The entire movie was of amazing quality with an unerring crystal clear sound.. Oh ! I am not canvassing for imax guys.. it's just that the technology amazes me.

Back to spidey... The instant hit formula of recapitulating the prequels during the title is what greets you as soon as the movie begins. And then you get to see what is quite unusual for an action flick... A song $#$%@@#$..! Spidey's gal is singin it and our spidey is a front bencher in the opera. Things are quite different in this spidey..

* The eternal belligerence between Mr.Jameson and Spidey seems to have abated.
* Spidey is no longer feared. He has now become the uncommonly common 'friendly neighbour'.
* Spidey can shake a leg or two.
* His gal knows that Spidey is Peter and gets ennerve of his success.
* Spidey makes a public appearance to cheer the kids.
* Spidey turns Romeo ! Finally decides to propose to MJ.
* Spidey knows how to forgive people.
and now the most important..
* Spidey aint a pizza boy any more..

Ahem, ahem...Okay.. I can see you getting the movie outline.. Nay ! c'on guys... after all spidey is one among the genetically branched out homo-sapiens.

Spidey's gal has been going through a rough patch where she finds herself as a restaurant singer from a Broadway star. And she expects spidey's 8th sense to tell him about her tragedy...no way..she wouldnt tell him her plight till the end. Now that unfortunately that strains their relationship..If that wasnt enough, during a public appearance, spidey manages to launch a kiss on the anchor girl(oh no.. not Shilpa again !! ). Yet another thorn.., the villain(???) forces MJ to say that she doesnt love Spidey any more. Gosh ! what a debacle.

Now if that wasnt enough trouble (Any mere mortal would have met his end trying to solve the previous bunch of problems), there are quite a number of 'yaenemies' for him to tackle. His former friend Harry still carries the grudge on Spidey for having killed his father and turns into the 'super goiyyaan' oops..Goblin.. and with his new found moves manages to keep the spidey webs at bay. A 'sand-man' (where do these ppl come from..?) seems to play havoc with the city's banks and later Spidey comes to know that he is the one responsible for his uncle's demise. No..No... wait.. there's more to it.. A symbiote (ET...! whoa ! way to go !) manages to crawl his way through to spidey. The symbiote can enhance the qualities of its host especially those of aggression. Now spidey gets attracted by the symbiotic suite (Dont ask me why it chose his suite as host rather than him..) and commits a series of mistakes before realising that the 'greatest battle lies within'. Finally he manages to rid himself off the symbiote only to pass it on to one of his professional (a photographer) rival, who uses the 'symbiotic power' (whoa ! that term is patented by Mighty-Titan) to seek revenge on spidey.

Now consider this equation of boolean algebra..

Let x = spidey, y= MJ.
let z= Harry.
let m= a photographer , n = the photographer's girl friend.

let -> represent unidirectional love

Then, x -> y.
y -> z apparently.
z -> y truely.
n ^-> x.
x = friend(z) - y.
y -> x truely - n.
z = enemy(x) + y.
m += x^->n?enemy(x):swornenemy(x).
m <-> n.
y ^-> z.

Well, if you can crack that.. you already have one of your foot in an IIT/IIM. Now now.. it aint that complex when are through with the movie. The plot unwinds solving one problem after the other and that is good news guys, coz Spidey can once more attend physics class (he is a class topper .. remember..?). After a couple of songs, a comedy track and a 'heart-touching' rendering of friendship, and a ultra-sacrifice the hero finally finds himself unshackled from all his troubles. Oh no.. have I mixed a bollywood movie ..? :P Think again....

To be fair guys..what I have stated is the post-movie analysis. It was an awesome movie to watch, a movie that you should definitely watch. The movie is packed with breath-taking graphics. The scene where the sandman is born is simply stupendous work. And the screenplay and stunts are something that you'll enjoy sans logic. The screenplay is extremely lucid and fast giving justice to the genre of the movie. Unlike other spidey movies, this one has a intricate mix of emotions which is what justifies the caption ..'The greatest battle lies within'. The entry of venom is quite refreshing and could possibly spawn spidey 4. After my recent movie debacles, it was quite a refreshing movie, one which takes you by storm for a little more two hours...

Technical References:
$gunu:bash$# Reference_1
$gunu:bash$# Reference_2
$gunu:bash$# Reference_3

Movie Bottom-Line : Bollywood graphicized.