Monday, October 05, 2009

Javascript handleEvent function

I just discovered this nifty little function!

handleEvent(evt) is basically the internal function which gets called when an event is raised on an object.

For example - when you attach a listener like so (jquery syntax ahoy) $('#divid').click(function(){blah blah}), what really happens is that the anonymous function is added to the event listeners list and the functions in that list are iterated over and called by the handleEvent function defined for DIVs. The anonymous function itself is not called directly when an event is raised.

Seems fairly useless until you realise that you can call this function yourself!

i.e. if you want some other div to handle the click event - use div.handleEvent(evt), passing it the event object!

I am sure it can be used for all sorts of nifty things, I just can't think of any practical examples right now.

TODO: Think of some practical examples.

Also, there is probably a way to attach events to custom objects which define the handleEvent function. Brainfreeze. Gotta try it out soon as I get out of this meeting.

TODO: Attach events to normal objects which define the handleEvent function.

1 comment:

jimisaacs said...

You are completely right. The advantage is that when the handleEvent method is invoked, it retains the scope of the object that was passed to the addEventListener method.

So:
obj = {
handleEvent: function() {
console.log(this); // The obj Object
}
}
window.addEventListener('load', obj);