Sencha Touch container tap events!

Sencha Touch is awesome, but sometimes can be frustrating. Some components just don’t have the events that you need. For example you can’t add a tap listener for a container inside of your controller’s config. I know you can add a listener on the component in the view, but I hate doing this because it moves controller logic in your view.

How do you get a container to listen for a tap event?

Since the component doesn’t have a tap listener we can add one to the components element object! Attaching a listener to the component’s element object gives you access to pretty much any event you will need. In this demo I’m going to use the tap event.

The view with the container component

Ext.define("MainView", {
    extend: 'Ext.Container',
    xtype: "main",
    name: "MainView",
    config: {
        layout: {
            type: 'fit',
            align: 'center',
            pack: 'center'
        },
        items: [
           {
            xtype: 'container',
            items: [{
                xtype: 'container',
                name:'clickableContainer',
                html: 'Hello there click me!'
            }, {
                xtype: 'container',
                html: 'Not clickable'
            }]
        }]
    }
});

The controller

Ext.define('MainController', {
	extend: 'Ext.app.Controller',
	config: {
		
	    control: {
	        MainView:{
		    initialize:'init'
		},
            },
	    refs: {
		MainView:"container[name=clickableContainer]",
	    }
	},
	init:function () {
          var containerView = Ext.ComponentQuery.query('container[name=clickableContainer]')[0];
	  var containerViewEl = containerView.element;
          containerViewEl.on('tap', 
            function( event, node, options, eOpts ){
         	alert('clicked the container');
    	    }
          );
	}
});

First thing we do is set up an init method, which is where we get a reference to the container view. Once we have the container view we can get the component’s element and use the on method to set up a listener (you could substitute the onBefore or onAfter method here), and just like that we have a container with a tap event!