Print Shortlink

A Link component with custom events in Ext JS 4

In the earlier post, we discussed creating a link component in Ext JS 4 using a template-based approach. In this post, let’s try to add our own events to the link component and register an event handler for the same.

Ext.Component class provides two methods addEvents and fireEvent which can be used for this purpose. Let’s add an event say “search” for the link component and fire the event when you click on the link.

The Link class with the search event is shown below.

	Ext.define("DuraSoft.custom.Link",{
			xtype : "link",
			extend : "Ext.Component",
			tpl : '<a href="{href}">{text}</a>',
			initComponent : function(){
				 this.data = {
						text : this.text,
						href : this.href
				}; 
				this.addEvents("search"); 
				this.callParent(arguments);
			}, 
			onRender : function(){
				this.callParent(arguments);
				this.mon(this.el,"click",function(){this.fireEvent

("search");},this);
			}	
		}); 

In the initComponent method we’ve added an event called “search”. The overriden onRender method fires the event when the component is clicked. Using the mon method, you can add a managed listener on the element for this event. We’ve added a listener for the click event. The handler function of click event fires the custom search event.

The code that uses this component with the event handler for search is shown below.

{
	xtype : "link",
	href:"http://www.google.com",
	text:"Search",
	listeners : {
	      			search : function(){alert("Searching!!!");}
		    }
} 

We’ll discuss some more examples on custom events in the subsequent posts.

Leave a Reply