Sencha add component inside XTemplate

Posted by | October 27, 2012 | JavaScript, Sencha | No Comments

Sencha touch is providing all the controls that you need to create any mobile application, but still what happens if you want to build your own custom component, well those nice guys that have invented the framework came with a solution on this problem, they created the XTemplats. In a few words this feature allows you binding stores from custom piece of HTML. This seams to solve any problem but what happens when you want to add a x-button or x-label inside the xtemplate. Well the documentation it says you can’t, I have struggled with this limitation and came up with a workaround. What I did was to dynamically create the sencha comportment and inject them using DOM selectors. This is depicted in the following lines of code

xtype : 'locate-grid',
	config :
		id : 'placeDetailsGrid',	
		store : 'PlaceDetailsStore',  //<-- binding the data store
		itemTpl : new Ext.XTemplate([ //<-- the template
		'<div class="place">', 
		'bla bla some HTML'				
				'<tpl for="coupons">', '<div class="couponContainer">', '<div class="couponSelect">',
				'<div class="select" id="coupon-select-{[]}"></div>', '</div>', '<div class="couponButton">', // <--- this is where is injected
				'</div>', '</div>', '</tpl>',
				'</div>' ].join('')),
		listeners :
			painted : function()
				var couponSelects ="#placeDetailsGrid .select");
				var checkboxComponents = this.getCheckBoxComponents();
				for ( var i = 0; i < couponSelects.length; i++)
					var select = couponSelects[i];
					if (checkboxComponents[i] == null)
						checkboxComponents[i] = new Ext.field.Checkbox(
							width : 40,
							label : '',
							labelAlign : 'right',
							labelWidth : '0%',
							checked : true,
							renderTo : select
					// TODO destroy this sometime

As you may have already observed this workaround has a disadvantage, all the dynamically create components are not managed by the framework, in other words you go to explicit destroy them. But still this solves the problem.

About Andrei Tara

Andrei is a developer/geek who loves creating high quality and efficient applications, always following the best practices in software engineering. He loves the challenge of learning new, exciting things and playing with new languages, frameworks, and tools.

Leave a Reply