Question

I have 4 buttons in Sencha touch. The text of each button is vote. I want that when the user taps on any of the buttons, the text of the corresponding button should be changed to 'Voted'. I want to write all this code in Controller in the best possible way.

Code:

buttons.js

items:
[
 {
     xtype:'button',
     text:"Item1",
     cls:'items'

  },

     xtype:'button',
     text:"Item2",
     cls:'items'

  },

     xtype:'button',
     text:"Item3",
     cls:'items'

  },

     xtype:'button',
     text:"Item4",
     cls:'items'

  },

]

Controller.js

control:
 {
   button:
     {
       tap:'OnButtonTap'
     }
 }
   OnButtonTap()
    {
      //how to get value of clicked button here
    }
Was it helpful?

Solution

Have a look at the documentation of the button tap event. The first parameter in the callback function is the button that was tapped. It can be used for immediate manipulations. Have a look at this working example at fiddle.sencha.com

Set up your app.js with the controller and view in place.

Ext.application({
    name : 'Fiddle',

    controllers: [
        'ButtonsController'
    ],

    views: [
        'ButtonsView'
    ],

    launch : function() {
        Ext.Viewport.add(Ext.create('Fiddle.view.ButtonsView'));
    }
});

The controller references the buttons and sets a new text on the button that has been tapped.

Ext.define('Fiddle.controller.ButtonsController', {
    extend: 'Ext.app.Controller',

    config: {
        refs: {
            button: 'buttonsview button'
        },
        control: {
            button: {
                tap: 'onButtonTap'
            }
        }
    },

    onButtonTap: function(button) {
        button.setText('Voted');
    }
});

The view holds the buttons. The defaults config comes in handy, too.

Ext.define('Fiddle.view.ButtonsView', {
    extend: 'Ext.Container',
    xtype: 'buttonsview',

    config: {
        layout: 'vbox',
        defaults: {
            xtype: 'button',
            cls: 'items'
        },
        items: [
            { text: 'Item1' },
            { text: 'Item2' },
            { text: 'Item3' },
            { text: 'Item4' }
        ]
    }
});

OTHER TIPS

You Should Assign a Unique Id to all the buttons, then write the following code for change the text of button.

In Sencha Touch you have to write the function as onButtonTap:function(){}

CODE :

OnButtonTap:function(button)
{
    Ext.getCmp(button.id).setText('Voted');
}

In above function the "button" is object that you clicked and you have access all the sencha touch button methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top