ExtJs 4 Toggle Button example

How to create a Toggle Button in ExtJs and capture the current state

In this example we have created a Button with the Toggle feature. The Toggle button can be either pressed or not. We start the button as pressed and then capture the state whether its pressed or not in the application controller. Here is the example...

extjs toggle button example extjs toggle button example

Application HTML file - index.html

<html>
<head>
<title>ExtJs 4 Toggle Button 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/toggleButton',
    
    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: 'Toggle button is currently Pressed',
                    action: 'myToggle',
                    pressed: true,
                    enableToggle: true
                }
            ]
        });
    }
}); 
    </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[action=myToggle]' : {
      toggle : this.onButtonPress
     }
    });
   },

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

   onButtonPress : function(button, pressed) {
    //console.log('Toggle Button was pressed', pressed);
    if(!pressed){
    button.setText('Toggle button is currently not Pressed');
    //you logic here
    }
    else {
    button.setText('Toggle button is currently Pressed');
    //your logic here
    }

   }

  });

References

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.