ExtJS Performance – Element click events

A question appeared on the ExtJS forums today regarding how to bind event listeners on multiple links that are generated from the server.  Bind an event listener to each link, right?  Wrong!  This is wrong in the sense that it wastes system resources and is unnecessary.  Can you imagine how much resources TreePanel would take up if it bound a click listener on every single node element!? Oh wait… that’s probably what you though it did :-).  But it doesn’t. 

The click listener is actually bound to the TreePanel element via its helper TreeEventModel.  So, there is only 1 click event listener for an entire tree. This magic happens because in browser land, events bubble up the dom. So when you click on a tree node you are clicking on the TreePanel up and up until the click is registered on the document body.

Finding the Clicked Element

You are probably wondering how you find the element that was clicked on.  Ext makes this really easy for us.  Take the following example:

So the magic is with the getTarget function which is defined on EventObject. You may find, depending on your html structure that when you click on something getTarget doesn’t return what you want. If I had an image inside the anchor tag getTarget would return a reference to the image and not the anchor tag. What should you do?

By using Ext.Element’s “up” method we are able to use css selectors to find the desired parent node.

Corresponding Record Reference

What if each anchor corresponds to a record which it can take action on when clicked. How do you determine which anchor matches up to which record when clicked. Again, lets take a page from TreeEventModel and do this the smart way. When you are generating your html, (hopefully you are using XTemplate), you should add an attribute to each indicating the record id it is paired to.


If you are doing work generating html with records you should probably look into using the Ext.DataView. It will do the record targeting for you. However, the technique I describe is very useful in a variety of situations. I use it for my breadcrumb toolbar to detect clicks on each breadcrumb link.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">