Sunday, March 3, 2013

ExtJs4 event handling. DOM Element event handling

Today I want to start new series on ExtJs4 event handling. The series are going to cover topics that might be interesting for beginners (like basic event handling of DOM Elements and ExtJs Components) as well as more advanced event handling related techniques and tricks (like event delegation and best practices for event handling in ExtJs MVC).
Without further ado let's dive into ExtJs4 DOM Elements event handling.
Ext.dom.Element is a DOM Element wrapper which encapsulates crossbrowser functionality for DOM manipulation. Although ExtJs is all about its Components (widgets) there might be cases where one would want to handle browser events of DOM Elements (for example constructing your own widget or adding some animations to page). In order to assign event handler to DOM Element one should use Ext.dom.Element's addListener method.
Consider that html page contains the following code:
<div id="example-node"></div>
To retrieve Ext.dom.Element for example-node one may use Ext.get method:
var exampleElement = Ext.get('example-node');
Since you retrieved corresponding Ext.dom.Element you can assign event handler to example-node using addListener method. Ext.dom.Element.addListener takes two parameters: event name and function (actual event handler). Now let's assume that we want to add click event handler to example-node (check out Ext.dom.Element documentation page for full list of available events).
Now let's check docs for click event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
exampleElement.addListener('click', function(e, t, eOpts){
  // handling event here
});
There is also Ext.dom.Element.on method which is shorthand for addListener method:
exampleElement.on('click', function(e, t, eOpts){
  // handling event here
});
I encourage you to use on rather than addListener method because of shorter syntax.

No comments:

Post a Comment