Tuesday 9 April 2013

How to access view component inside controller in Sencha Touch 2

In order to access the view component inside controllers, sencha touch 2 provides refs config property. refs makes it easy to get reference of view component available in the page using collection of named ComponentQuery selectors.

Let's demonstrate this by creating a Panel Component and access the panel component in controller using different ways.

Define a view Panel Class
Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.Panel',
    alias: 'widget.mypanel',

    config: {
        html: 'My Panel Content1',
        itemId: 'panelId',
        styleHtmlContent: true
    }
});

Define a Controller Class
Ext.define('MyApp.controller.MyController', {
    extend: 'Ext.app.Controller',

    config: {
        refs: {
            myPanel: '#panelId'
        },
        control: {
            "panel": {
                initialize: 'onPanelIdInitialize'
            }
        }
    },
    onPanelIdInitialize: function(component, options) {
        var panelview = this.getMyPanel();
        Ext.Msg.alert(panelview.getHtml());
    }
});

Access View component inside Controller

Option1:

You can able to access the panel component using itemId (#panelId) config property.
refs: {
    myPanel: '#panelId'
}

Option2:

You can also access panel component using xtype. Inorder to achieve this, you need to use the below refs config property.
refs: {
    myPanel: 'mypanel'
}

Option3:

You can also access panel component using both selector and xtype config property. Inorder to achieve this, you need to use the below refs config property.
refs: {
    myPanel: : {
        selector: '#panelId',
        xtype: 'mypanel',
        autoCreate: true
    }
}

autoCreate config property will first run the ComponentQuery to see if a Component matching that selector exists on the page. If not, it will automatically create one using the xtype provided.

When you run this code in Google chrome, you will get the alert popup message shown below for all above three options.



Hope, you enjoyed this Post.

No comments:

Post a Comment