Blog Archive

ExtJs 4 button click example

How to capture the click event of a button in ExtJs controller

In this example we will create a couple of buttons on the page and then listen for the click event in the controller. After that we can query which button was pressed and take appropriate action.

extjs button click example

Application HTML file - index.html

<html>
<head>
<title>ExtJs button click example</title>

<link rel="stylesheet" type="text/css"
 href="extjs/resources/css/ext-all.css">
<style type="text/css">
</style>
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript">
Ext.Loader.setConfig({ 
 enabled: true 
 });

Ext.application({
    
 name: 'myApp',
 appFolder: 'app/buttonClick',
    
    controllers: [
                  'MyController'
              ],

    launch: function() {
 Ext.create('Ext.container.Container', {
         renderTo: 'myExample',
         height: 250,
            width: 400,
         layout: {
                align: 'stretch',
                type: 'vbox'
            },
         defaults: { 
            labelWidth: 150,
            margin: '5 5 5 5 '
         },
            items: [
                {
                 xtype: 'button',
                    text: 'My First Button'
                },
                {
                 xtype: 'button',
                    text: 'My Second Button'
                },
                {
                  xtype: 'displayfield',
                    fieldLabel: 'You clicked on the',
                    name: 'whichButton',
                    itemId: 'whichButton',
                    value: ''
               }
            ]
        });
    }
}); 
    </script>

</head>
<body>
 <div id="myExample"></div>
</body>
</html>

Application Controller - MyController.js

Ext.define('myApp.controller.MyController', {
   extend : 'Ext.app.Controller',

   init : function() {
    this.control({

     'container' : {
      render : this.onContainerRendered
     },
     'container button' : {
      click : this.onButtonClick
     }
    });
   },

   onContainerRendered : function() {
    //console.log('The container was rendered');
   },

   onButtonClick : function(button) {
    //console.log('Button Click');
    var myView = button.up('container');
    var myTextDisplay = myView.getComponent('whichButton');
    myTextDisplay.setValue('<b>' + button.getText() + '</b>');

   }

  });

References


No comments :

Post a Comment