ExtJS - Event Handling

extjs

http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.dom.Element-method-on
EventObject
http://neiliscoding.blogspot.com/2011/09/add-custom-events-in-extjs-4-basic.html

Where can we find a list of events supported?

abort
blur
change
click
contextmenu
dblclick
error
focus
keydown
keypress
keyup
load
mousedown
mouseenter
mouseleave
mousemove
mouseup
reset
resize
scroll
select
submit
unload
  1. http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.dom.Element-event-abort

It seems that ExtJS also support the following event types:

  1. copy
  2. paste

I am not sure if there is an authoritative list of events that ExtJS support. I need to look for this. Keep in mind that each type of component has its own list of events. Check the documentation for the component.

How to implement basic event handling on a DOM element?

Ext.get('myButton').on('click',function(){}, scope, options);
Ext.select('p').on('click',function(){}, scope, options);

The .on() method is a shorthand for the addListener method. It takes 2 to 4 parameters. The first two parameters (the event name, and the handler function) are required. The last two parameters (scope, and option) are optional. Scope is an object in which the handler function is executed (inside the handler function, the this keyword reference this object). If omitted, defaults to this Element..

ExtJS pass three parameters to our event handler function:

  1. The first parameter is an Ext.EventObject, which is normalized across browsers and provides more information than standard browser event. For example, the event's target DOM node can be retrieved with e.target. Note that target is a DOM node, so we must first retrieve the corresponding Element, then perform whatever action we want on it.
  2. The second parameter is an Element which was the target of the event. Note that this may be filtered by using the delegate option.
  3. The third parameter is the options object from the addListener call.

The options is an object containing handler configuration properties. This may contain any of the following properties:

  • scope (Object): The scope (this reference) in which the handler function is executed. If omitted, defaults to this Element.
  • delegate (String): A simple selector to filter the target or look for a descendant of the target. See below for additional details.
  • stopEvent (Boolean): True to stop the event. That is stop propagation, and prevent the default action.
  • preventDefault (Boolean): True to prevent the default action
  • stopPropagation (Boolean): True to prevent event propagation
  • normalize (Boolean): False to pass a browser event to the handler function instead of an Ext.EventObject
  • target (Ext.Element): Only call the handler if the event was fired on the target Element, not if the event was bubbled up from a child node.
  • delay (Number): The number of milliseconds to delay the invocation of the handler after the event fires.
  • single (Boolean): True to add a handler to handle just the next firing of the event, and then remove itself.
  • buffer (Number): Causes the handler to be scheduled to run in an Ext.util.DelayedTask delayed by the specified number of milliseconds. If the event fires again within that time, the original handler is not invoked, but the new handler is scheduled in its place.

Using the options argument, it is possible to combine different types of listeners. An example of specifying the options object:

el.on('click', this.onClick, this, {
    single: true,
    delay: 100,
    stopEvent : true,
    forumId: 4
});

The options object is passed to the event handler function as the third argument.

Example of event handling inside a component:

listeners: {
    afterrender: function() {
        var dom = Ext.get('docDesc');
        dom.on('paste', function(event,element){
            //event.stopEvent();
        });
        dom.on('copy', function(evt,element){
            evt.stopEvent();
        });
        dom.on('keyup', function(evt,el){
            var documentDesc = strTrim( Ext.get('docDesc').dom.value );
            var remaining = 1000 - documentDesc.length;
            if ((remaining <= 0) && (! evt.altKey) && (! evt.ctrlKey)) {
                // evt.stopEvent();
            }
        });
    },
    change: function() {
        me.validateAttachment();
        me.updateCharacterCount();
    }
}

How to install multiple event handlers in one shot?

el.on({
    'click' : {
        fn: this.onClick,
        scope: this,
        delay: 100
    },
    'mouseover' : {
        fn: this.onMouseOver,
        scope: this
    },
    'mouseout' : {
        fn: this.onMouseOut,
        scope: this
    }
});

Or a shorthand syntax:

el.on({
    'click' : this.onClick,
    'mouseover' : this.onMouseOver,
    'mouseout' : this.onMouseOut,
    scope: this
});

How to implement event delegation with ExtJS?

This is a configuration option that you can pass along when registering a handler for an event to assist with event delegation. Event delegation is a technique that is used to reduce memory consumption and prevent exposure to memory-leaks. By registering an event for a container element as opposed to each element within a container. By setting this configuration option to a simple selector, the target element will be filtered to look for a descendant of the target. For example:

// using this markup:

<div id='elId'>
    <p id='p1'>paragraph one</p>
    <p id='p2' class='clickable'>paragraph two</p>
    <p id='p3'>paragraph three</p>
</div>
// utilize event delegation to registering just one handler on the container element: 

el = Ext.get('elId');
el.on(
    'click',
    function(e,t) {
    },
    this,
    {
        delegate: '.clickable' 
    }
);

How to pass additional parameters to the event handler function?

I am not sure why or when we need to pass additional parameters to the event handler.

The options literal you can pass as fourth argument configures the listener (settings like delay, scope, …). You can not use it to pass extra arguments to the listener function. That's where createDelegate comes in.

var a = new Ext.Button({ text: 'Click!', renderTo: Ext.getBody() });

a.on('click', function(){
    alert('click after 2 seconds!');
    console.log(arguments); // will log the strings 'Hello' and 'World'
}.createDelegate(a, ['Hello', 'World']), null, { delay: 2000 });

The Function module in ExtJS contains createDelegate, createCallback, createInterceptor, createSequence, defer methods.

Here's a quick example on how to pass arguments to an event handler using createDelegate:

var someHandler = function(evt,t,o,myArg1,myArg2,myArg3) {
        //do stuff
}
Ext.select('.notice-type1').addListener('click', someHandler.createDelegate(this, [4,'pizza',11], true));
Ext.select('.notice-type2').addListener('click', someHandler.createDelegate(this, [7,'stuff',12], true));

evt, t, o: These are the arguments that would get passed to your event handler normally. They are: the EventObject describing the event, the Element which was the target of the event, and the options object from the addListener call. See addListener in the API for more information. You can also set a breakpoint in Firebug inside your event handler to check these objects out and see what kind of useful things they contain.

myArg1, myArg2, myArg3: your own custom arguments specified as an array which is passed as the second argument to createDelegate. In this case we're passing 4,'pizza',11 for elements of class "notice-type1" and 7,'stuff',12 for elements of class "notice-type2".

If all you want to do is pass custom arguments to the even handler and you don't need to have access to the element that fired the event you're probably better off just using createCallback.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License