Print Shortlink

A Link component in Ext JS 4 – Template-based approach

In the earlier post, we discussed creating a link component in Ext JS 4 using the autoEl property. The autoEl object is initialized with the values passed during the creation of the link component. Let’s create the following link component using a template-based approach.

{
        xtype : "link",
        href : "http://www.google.com",
        text : "Search"
}

Instead of using the autoEl property which renders the tag, you’ll define the complete html that you want to be rendered. We’ll use tpl property of the Ext.Component class to define a html template. The tpl property will look like

tpl : "<a href={href}>{text}</a>"

The {href} and {text} expressions will be replaced with the actual values passed through the data property as shown below.

data : {
		href : "http://www.google.com",
		text : "Search"
}

The complete Link component is shown below.

Ext.define("DuraSoft.custom.Link",{
			xtype : "link",
			extend : "Ext.Component",
			tpl : '<a href="{href}">{text}</a>',
			 data : {
				href : "http://www.google.com",
				text : "Search"
			} 
		});

The code above has hardcoded data. You can initialize the data property dynamically with the values passed during creation of the component as 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
				};  
			} 
});

As you can see, the template-based approach is preferred in case of complex components as it gives you more flexibility.

Leave a Reply