ExtJS Performance – Event Listener Cleanup

Its a pretty simple code snippet but the overarching topic, performance (especially in ExtJS), can be complicated and developers really need to be cognizant of performance impacts.  Especially so when its running on the client which you have no control over the performance specs of the machine.

There has long been the problem in Ext with the issue of cleaning up event listeners after the listening component has been destroyed.  Until now, developers have had to code custom destructors to handle this cleanup.

Lets say you have an Ext interface where you can open multiple tabs to edit database backed Ext.data.Records.  You will probably want the tabs to listen to a given record’s Ext.data.Store’s update event so that if a particular piece of data is updated elsewhere in your interface, the change will be reflected in the open tab as well.  The problem here is that when you close (destroy) that tab the event listener you registered on the Ext.data.Store hangs around.  Over time, from opening and closing many of these tabs, you can build up a huge number of listeners that should no longer exist.  All of these listeners are still called, and their code still runs. Worse yet, since they most likely contain a references to other objects through closures, or scope bindings, that memory will never be cleaned up!

So, when you have an Ext.Component that binds event listeners on an Ext.util.Observable object that will persist beyond the lifecycle of the Component, you will get memory leakage, performance impacts, and quite likely, errors.

The great news is that ExtJS 2.1 now supports automatic cleanup of event listeners!  No more Ext hacks!  Here is how it works:

Normally you would bind an event listener like this: (pretend this code appears inside your Ext.Panel constructor)

Now, you should instead register events like this:

So, this hidden nugget “mon” (on Ext.Component) will clean up the event listener when “this” is destroyed. This is also very useful for DOM event listeners:

Thats all for now! I have a lot of other Ext performance tips and tricks so I will try to get to those in later posts.

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="">