RSS

Prototype Event.observe

16 May

New version 1.6 of Prototype library now supports this within an event handler as a reference to the element the handler is associated with.

The reason I am excited about this is that due to the incompatibilities between W3C and Microsoft event models this doesn’t always work how you would expect it to. In JavaScript you would expect this keyword to point to the “owner” of the function – in the case of event handlers to an element the event is handled by.

Let’s have a look on how event handlers are registered and how to access an HTML element the event is handled by. There are 4 different models to register an event handler: inline, traditional, W3C and Microsoft advanced models. Now we are particularly interested in advanced model which I believe Prototype is using for the Event.observe method. If you want to know more on events check quirksmode.org.

W3C model

To register a function func to the onclick of an elem element you do

var func = function{
    this.style.color = 'blue';
}

elem.addEventListener('click', func, false)

In the above example when onclick event occurs the function func is executed and elem text colour changes to blue. As you can see in the W3C model this refers to the elem element. Try this test example.

Microsoft model

To attach an event handler in Microsoft model attachEvent method is used. Note, event name for attachEvent differs from one for W3C model. Let’s try and use the same func function:

elem.attachEvent('onclick',func)

If you try this example you will get en error. Unlike W3C, this in Microsoft model refers to the window object. This happens because the event handling function is referenced but not copied.

Now back to Prototype Event.observe method. Consider the following example with the same func function:

Event.observe($("elem"), "click", func);

Starting version 1.6 this code works correctly in all browsers. Check the prototype section of the example.

Thank you Prototype!

Advertisements
 
Leave a comment

Posted by on May 16, 2009 in JavaScript

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: