Tuesday, March 5, 2013

ExtJs4 event handling. Components event handling

This is continuation of ExtJs4 event handling series. Today we are going to dug into ExtJs Components event handling.
Ext.Component is a core class of ExtJs that is extended by all built-in widgets (like Panel, Grid, etc). So everything I will talk about today may be applied to every widget that extends Ext.Component.
Event handling in components is provided by Ext.util.Observable. Everything that contains Ext.util.Observable as a mixin is ready to fire events and attach event listeners. So everything I will talk about today may be applied not only to every widget that extends Ext.Component but to every class that contains Ext.util.Observable as a mixin.
Ext.util.Observable provides us with two ways of assigning event handlers.
Firstly we may use on method (on is a shorthand for addListener). on takes event name as the first parameter and event handler function as the second one. For the full list of built-in events and parameters that they pass to event handlers check out docs for the desired component.
someComponent.on('click', function(me, e, eOpts) {
  // event handling here
});
The second way is to use listeners config. listeners is an object each key of which is event name and value is event handler function:
Ext.create('SomeComponent', {
  // ...
  listeners : {
    click: function(me, e, eOpts) {
      // event handling here
    }
  }
});

Custom Events

Ext.util.Observable provides us with functionality of firing custom events. In order to fire custom event of SomeComponent just call fireEvent method. fireEvent takes event name as the first parameter. Every variable passed to fireEvent method as a parameter (starting from the second position) will be passed into event handler. So for example firing event
someComponent.fireEvent('customevent', arg1, arg2);
will cause passing arg1, arg2 into event handler that listens customevent:
someComponent.on('customevent', function(arg1, arg2) {
  // event handling here
});

Demo

In the demo custom class MyCustomGrid which extends Ext.grid.Panel is created. Custom event evenitemdeleted is fired whenever item with even id is deleted. Items can be deleted from grid by doubleclicking the corresponding row.

No comments:

Post a Comment