ExtJS Toolbars Menus Buttons

16
Ext JS Toolbars, Menus and Buttons Guide David Feinberg Copyright © 2011 Sencha, Inc. All rights reserved. Pre-Release Content All the content in this guide is based on a early pre-release version of Ext JS 4. The concepts and code examples presented in this guide may not be applicable to the final release.

Transcript of ExtJS Toolbars Menus Buttons

Page 1: ExtJS Toolbars Menus Buttons

Ext JS Toolbars, Menus and Buttons GuideDavid FeinbergCopyright © 2011 Sencha, Inc. All rights reserved.

Pre-Release Content

All the content in this guide is based on a early pre-release version of Ext JS 4. The concepts and codeexamples presented in this guide may not be applicable to the final release.

Page 2: ExtJS Toolbars Menus Buttons

iii

Table of Contents5. Toolbars, Buttons & Menus .......................................................................................... 1

............................................................................................................................... 1Overview ................................................................................................................. 1Introduction to Ext.Toolbar ....................................................................................... 1Introduction to Ext.Button ......................................................................................... 3Introduction to Ext.Menu .......................................................................................... 4Arranging Toolbar Items ........................................................................................... 7Putting Toolbars, Buttons and Menus to Work ......................................................... 10Links ..................................................................................................................... 13

Page 3: ExtJS Toolbars Menus Buttons

iv

List of Figures5.1. Toolbars Alone and Docked to a Panel. ..................................................................... 15.2. Buttons Within a Toolbar and Alone ........................................................................... 35.3. CSS File ................................................................................................................... 45.4. Menus in a Toolbar and Alone ................................................................................... 55.5. CSS File ................................................................................................................... 75.6. Toolbar arrangement and overflow ............................................................................. 85.7. Displaying an Alert Message Box on Menu Item Click ............................................... 11

Page 4: ExtJS Toolbars Menus Buttons

1

Toolbars, Buttons & MenusAll the content in this guide is based on a early pre-release version of Ext JS 4. The conceptsand code examples presented in this guide may not be applicable to the final release.

OverviewThis guide provides a series of examples to help you start working with Ext.Toolbar, Ext.Menuand Ext.Button components. You'll learn how these three components work individually andtogether to provide an integrated set of tools for user interaction.

Introduction to Ext.ToolbarThe Ext.Toolbar component is designed to make it easy to add toolbar interfaces to yourExt JS powered applications. Toolbars commonly contain different types of Ext.Buttonand Ext.menu.Menu components for user interaction. In addition to holding Menus andButtons Ext.Toolbar extends Ext.Container which allows it to contain any descendant ofExt.Component one of the core framework classes. This flexibility allows you to customizeToolbars to support a wide range of user interface solutions.

Let's jump right into it and see how quickly we get some toolbars displayed on-screen. AnExt.Toolbar component can be displayed anywhere in an Ext JS application although mostof the time you'll be working with Toolbars that are docked inside Panels and componentsthat subclass Ext.Panel. In this example we'll display a few empty toolbars on-screen. One isconfigured to display outside of the Panel and the other two are docked to the top and bottomof the Panel.

Figure 5.1. Toolbars Alone and Docked to a Panel.

Page 5: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

2

Ext.onReady(function() { var sampleToolbar = new Ext.Toolbar({ // 1 width: 400, height: 40, renderTo: Ext.getBody(), // 2 style: { marginBottom: '20px'} // 3 });

var samplePanel = new Ext.Panel({ // 4 width: 400, height: 300, title: "Panel with Top & Bottom Toolbars", tbar: { // 5 height: 30 }, bbar: { // 6 height: 30 }, renderTo: Ext.getBody() }); });

1. The first Toolbar is created by instantiating a new Ext.Toolbar component and setting a fewbasic configuration options to specify height, width and rendering.

2. The first Toolbar renders directly to the document body retrieved with the utility methodExt.getBody on the global singleton Ext.

3. A 20 pixel margin is added to the bottom of the Toolbar using the style config option. Thisprovides some space between the first Toolbar and the Panel below it.

4. We instantiate an Ext.Panel that we'll dock our Toolbars to.

5. Here we set the Panel's tbar configuration option to a Ext.Toolbar configuration object (thesame one we could use to instantiate an Ext.Toolbar directly). This is a nice convenienceprovided by Ext.Panel which uses the configuration object we set here to automaticallycreate an Ext.Toolbar instance for us and docks it to the top of the Panel.

6. The bbar option works just like tbar allowing us to set an Ext.Toolbar configuration objectthat's used to automatically create a bottom Toolbar for the Panel.

By setting the tbar and bbar configuration options we were able to quickly add top and bottomToolbars to a Panel. In this example we set these values with a Toolbar configuration object.In addition to that approach both tbar and bbar can also be set with an existing Toolbar objector directly with an array of button configuration objects and it will automatically perform theappropriate actions to create a Toolbar instance and dock it to the Panel. Now that you've seenhow easy it is to work with an empty Toolbar we'll go over the most common components toadd to start bringing our Toolbars to life.

Page 6: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

3

Introduction to Ext.ButtonExt.Button is a versatile component that can be used to add many different types of buttonsto Ext JS applications. Built-in configuration options are available for creating common buttontypes including; text buttons, icon driven buttons and menu buttons. The flexible design ofExt.Button makes it a great building block for custom button implementations.

Let's get started seeing a few different types of buttons in action then we'll go over the code weused to create them. Like toolbars buttons can be used completely on their own or combinedwith other Ext Components.

Figure 5.2. Buttons Within a Toolbar and Alone

Ext.onReady(function() { var sampleButton = new Ext.Button({ // 1 text: 'Text Button', renderTo: Ext.getBody() });

var samplePanel = new Ext.Panel({ width: 400, height: 300, title: "Top Toolbar with Buttons",

Page 7: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

4

tbar: { items: [{ xtype: 'button', // 2 text: 'Refresh' }, { xtype: 'button', iconCls: 'email-add-icon', // 3 text: 'New Message' }] }, renderTo: Ext.getBody(), style: { marginTop: '20px'} }); });

Figure 5.3. CSS File

.email-add-icon { background-image: url(images/email_add.png); }

1. Here we're creating an instance of the Ext.Button class just by setting two configurationoptions text and renderTo. This creates a button labeled "Text Button" and renders it to thedocument body.

2. Next we setup a top Toolbar within our Panel. The Toolbar is configured with an array ofButton configuration objects. The first is a simple text button labeled "Refresh".

3. For the second Button we set the iconCls config option to "email-add-icon" which is a CSSclass that sets the background image of the Button to an icon referenced in a CSS file(shown below the JavaScript). For this example we're using an 16x16px image from theFamFamFam Silk icon library. You can use any image you want and the Button object willautomatically size itself to fit the image.

This example demonstrated how to begin working with the Ext.Button component. Werendered a Button on its own and a couple inside a Toolbar using the convenience of xtypes.We saw some examples of common Button types and Button configuration options. We'llcontinue building on this example by adding menus to the Toolbar next.

Introduction to Ext.MenuThe Ext.menu.Menu component provides integrated menu capabilities for Ext JS components.The Ext.menu package includes classes for a number of common Menu Items thatExt.menu.Menu works with out-of-the-box. In addition to the built-in Menu Item classesExt.menu.Menu can also be used to hold any component that descends from Ext.Componentincluding all the components in the Ext.form package. Ext.menu.Menu is a flexible componentfor creating menu driven interfaces and can be extended to create completely custom Menuimplementations.

In this example we'll see how using Ext.menu.Menu by itself simply provides a specializedtype of Container for holding menu items. Then we'll demonstrate how the Menu componentbecomes practical when combined with other Ext components. Here we'll combine it withExt.Button to quickly create different types of Menu Buttons.

Page 8: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

5

Figure 5.4. Menus in a Toolbar and Alone

At the top we're displaying a Ext.menu.Menu component entirely on its own just to show whatan isolated Menu looks like. This is the same way a context menu would display if a user rightclicks on a Ext.GridPanel that has its contextmenu option configured. Under the floating menuthe single panel from the code example is shown three times to demonstrate how each of theMenus look with different configuration options applied.

new Ext.menu.Menu({ items: [{ // 1 text: "<b>Bold</b>" }, { text: "<i>Italic</i>" }, { text: "<u>Underline</u>" }], floating: false, // 2 width: 100, // 3 renderTo: Ext.getBody() });

1. A new Ext.menu.Menu object is instantiated here and Ext.menu.Item components arecreated just by setting the text configuration value for each item. This works withoutexplicitly setting an xtype because the default xtype for Ext.menu.Menu is already set toExt.menu.Item

2. The floating config option is set to false here to make sure the Menu is displayed in aviewable area. By default Menu will be rendered in a floating Ext.Layer and absolutelypositioned off-screen. This is by design as in most cases you'll be using Menu with other Extcomponents and you'll want to control exactly where the menu appears using show, showAtor setPosition among other configuration options.

3. Here the width config is set to 100 pixels to keep the menu size appropriate for the itemswe're displaying.

Page 9: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

6

new Ext.Panel({ width: 290, height: 300, title: "Toolbar with Button Menus", tbar: { items: [{ xtype: 'button', text: 'Simple Menu', menu: { // 4 showSeparator: false, // 5 items: [{ text: 'menu item one' }, { text: 'menu item two' }] } },

4. For the first item in the Toolbar we setup a simple text Ext.Button and set the Button's menuconfig option with an Ext.menu.Menu configuration object. By setting the Button's menuconfig it will automatically create an instance of Ext.menu.Menu for us and display it whenthe button is clicked. You can also programmatically show and hide the Menu using theButton's showMenu and hideMenu methods.

5. The showSeparator config option is set to false here to demonstrate how you can removethe incised line along the left side of the menu which looks a bit cleaner for menuscontaining all text items.

{ xtype: 'button', iconCls: 'email-add-icon', text: 'Message Type', menu: [{ // 6 text: 'email message', iconCls: 'email-icon' },{ text: 'sms message', iconCls: 'email-icon' },{ text: 'push message', iconCls: 'email-icon' }] }, { xtype: 'splitbutton', // 7 text: 'Split Button', iconCls: 'user-add-icon', menu: [{ text: "<b>Bold</b>" },

Page 10: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

7

{ text: "<i>Italic</i>" }, { text: "<u>Underline</u>" }] }] }, renderTo: Ext.getBody(), style: { marginTop: '20px'} }); });

6. For the second Menu Button an array Ext.menu.Item configuration objects is set for thevalue of menu instead of an Ext.menu.Menu configuration object to demonstrate anotherway of configuring a Menu Button. We also use the iconCls as we did before along withsome CSS to display an icon to the left of the Menu Item's text.

7. For the last Button in the Toolbar the xtype is set to splitbutton which creates anExt.SplitButton instead of the Ext.Button objects we used for the first two buttons in theToolbar. Ext.SplitButton creates a built-in dropdown arrow allowing the user to triggerdisplaying the Menu separate from clicking the Button. This design fires two unique eventswhich gives you the ability to execute different code depending on where the user clicks.We'll walk-through an example of how this works later in this guide.

Figure 5.5. CSS File

.email-icon { background-image: url(images/email.png); } .email-add-icon { background-image: url(images/email_add.png); } .user-add-icon { background-image: url(images/user_add.gif); }

After exploring the code for this example you should have a good grasp on how to startworking with Ext.menu.Menu class and integrating some basic Menus, Buttons and Toolbarstogether. Up until now we've been adding components to our Toolbar without paying muchattention to arranging Toolbar items. In the next example we'll explore the Toolbar layout andsome special Toolbar Items you can use to control the spacing and positioning of componentsin your Toolbars.

Arranging Toolbar ItemsBy default Ext.Toolbar uses Ext.layout.ToolbarLayout to arrange the items it contains. TheToolbarLayout is designed to arrange items side-by-side across the horizontal length of theToolbar. Beyond basic layout controls ToolbarLayout also has the ability to automaticallyprovide users with access to items that overflow the Toolbar through a dynamically generatedExt.menu.Menu that holds overflowed items as the size of Toolbar is adjusted directly or by acontaining component.

In addition to arranging Toolbar items with the ToolbarLayout Ext JS also provides threespecialty Toolbar Items (Fill, Separator and, Spacer) that can be added to Toolbars to controlspacing and separation between items. We'll go through a small example to demonstrate howyou can use these tools to arrange Toolbar items.

Page 11: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

8

Figure 5.6. Toolbar arrangement and overflow

In this example six different Buttons are configured inside a Toolbar to demonstrate how youcan use some of the built-in configuration options of classes in the Ext.Toolbar package toarrange Toolbar items directly from JavaScript without diving into the underlying CSS.

Ext.onReady(function() { new Ext.Panel({ width: 430, height: 300, title: "Arranging Toolbar Items", tbar: { enableOverflow: true, // 1 items: [{ xtype: 'button', text: 'Text Menu', menu: { plain: true, showSeparator: false, items: [{ text: 'menu item one' }, { text: 'menu item two' }, { text: 'menu item three' }] } },

Page 12: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

9

1. Here the enableOverflow option of the Toolbar is set to true so it automatically displaysa drop down menu allowing users to access items that don't fit inside the specifiedwidth. In this example the Toolbar width has been purposely constrained to 430 pixels todemonstrate how the last two Buttons look when they automatically appear in the overflowmenu.

NoteThe default value for enableOverflow is false causing overflowed items to displayclipped or outside the viewable area of the Toolbar.

{ xtype: 'tbspacer', // 2 width: 20 }, { xtype: 'button', iconCls: 'email-add-icon', text: 'Messages', menu: [{ text: 'email message', iconCls: 'email-icon' },{ text: 'sms message', iconCls: 'email-icon' },{ text: 'push message', iconCls: 'email-icon' }] },

2. The xtype tbspacer is used here to reference Ext.Toolbar.Separator. This providesa convenient way to specify spacing between Toolbar items simply by including aExt.Toolbar.Separator configuration object between the items you want to separateand setting a value in pixels for its width. This is one of the three built-in subclasses ofExt.Toolbar.Item designed to make it easier to arrange items inside Toolbars.

{ xtype: 'tbfill' // 3 }, { xtype: 'button', text: 'Right Button' }, { xtype: 'tbseparator' // 4 }, { xtype: 'splitbutton', text: 'Split Button', iconCls: 'add16',

Page 13: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

10

menu: [{ text: "<b>Bold</b>" }, { text: "<i>Italic</i>" }, { text: "<u>Underline</u>" }] }, { xtype: 'button', text: 'Overflowed Text Button' }, { xtype: 'button', iconCls: 'email-icon', text: 'Overflowed Icon Button' }] }, renderTo: Ext.getBody() }); });

3. Here the tbfill xtype is used to reference Ext.Toolbar.Fill which changes the alignmentof Toolbar items added from that point on to become right-justified instead of the defaultleft-justified style. In this example tbfill is responsible for causing all the renaming buttonsstarting with the button labeled "Right Button" to be right-justified.

4. The tbseparator xtype is included between the buttons labeled "Right Button" and "SplitButton" to display a visual separator between the two items in the form of a dotted verticalline. This is a common user interface element conveniently included in Ext JS to make iteasy to visually group similar buttons together inside your Toolbars.

Note

Although it's possible to override the default ToolbarLayout it's not recommendunless you have a highly specialized use case for using another layout.

Putting Toolbars, Buttons and Menus to WorkNow that we've explored how to configure and arrange Toolbars, Buttons and Menus it's timeto actually put these components to work for us by showing how you can wire up some simpleJavaScript functions that will execute as you interact with these controls.

Similar to the previous examples we'll display a few types of Buttons inside a Toolbar thenwe'll take things one step further by wiring up event handlers to respond to some of the built-in Button events. We'll also go over a couple techniques to access the components containingour Menus and Buttons to provide a glimpse at how you might use these components togetherin a real-world application.

Page 14: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

11

NoteThe code we'll explore is designed to demonstrate specific concepts in ashort block of code. The pattern shown here shouldn't be used as a modelfor constructing large-scale applications. We'll cover best practices for codeorganization and application architecture in more advanced guides.

Figure 5.7. Displaying an Alert Message Box on Menu Item Click

This example sets up a Panel with a Toolbar containing three items, a standard Button,SplitButton and, a spacer between them. Two different techniques are used to demonstratehow functions can be executed when a Button or Menu Item is clicked. Within these functionsyou'll see a few different ways to access the Toolbar and Panel that contain the Buttons andMenu Items. This is a common pattern in real-world applications where toolbar items usuallyallow users to perform actions on surrounding interface components. To keep things simplethis example displays some simple messages when components are clicked. Although wecould have used the standard JavaScript alert box we introduce Ext.Msg.alert which is aspecialized Ext JS styled MessageBox that provides a convenient way to display messagesconsistent with the look and feel of your overall application.

Ext.onReady(function() { new Ext.Panel({ width: 350, height: 300, title: "Wiring Up Toolbars, Buttons & Menus", tbar: { items: [{ xtype: 'button', iconCls: 'email-icon', handler: function(buttonObj, eventObj) { // 1 var tbrItemCount = buttonObj.ownerCt.items.length; // 2 Ext.Msg.alert("Message", "I'm in a Toolbar containing " + tbrItemCount + " items."); // 3 },

Page 15: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

12

text: 'View Messages' },

1. The function set for the handler configuration option automatically executes when the Buttonis clicked passing in two values; the Button object itself and an instance of Ext.EventObjectwhich wraps the native browser click event.

2. The ownerCt property of the Button object allows you to access the owner container of theButton which in this example is the Toolbar. The items property of the Toolbar contains thecollection of three components (two buttons and a spacer between them) that we set for theToolbar using the items confguration option. A local variable tbrItemCount is used to holdthe number 3, the length of the Toolbar's items collection.

3. Ext.Msg.alert displays a themed alert style MessageBox when the Button is clicked. TheMessageBox is passed two strings. The first string appears in the title area of the box andthe second displays inside the box along with an "OK" Button that automatically closes thebox when clicked just a like a regular JavaScript alert box.

{ xtype: 'tbspacer', width: 5 }, { xtype: 'splitbutton', iconCls: 'email-add-icon', text: 'New Message', listeners: { // 4 'arrowclick': function(buttonObj, eventObj) { Ext.Msg.alert("Message", "You clicked the menu arrow!"); }, 'click': function(buttonObj, eventObj) { Ext.Msg.alert("Message", "You clicked the '" + buttonObj.text + "' button."); } },

4. Here a SplitButton is being used to demonstrate how you can setup two different functionsto execute depending on whether the user clicks the actual Button or the Menu arrow. Thelisteners configuration option is used instead of the handler option that was used for theprevious Button. While the handler option is a convenient way to execute a function when aButton's click event is fired using the listeners option allows you to setup handler functionsthat can be configured to execute when any of the available Button events are fired. Herethe first function is configured to execute when the arrowclick event fires (whenever theMenu arrow is clicked). The second function is set to execute when the Button's click eventis fired (whenever the Button is clicked). The latter works the same as if you had set thefunction using the handler option. When executed both functions display a message insidean Ext.Msg.alert box.

menu: [{ text: 'email message', iconCls: 'email-icon', listeners: {

Page 16: ExtJS Toolbars Menus Buttons

Toolbars, Buttons & Menus

13

'click': function(menuItemObj, eventObj) { var panelTitle = menuItemObj.findParentByType('panel').title; // 5 Ext.Msg.alert("Message", "Menu Item: \"" + menuItemObj.text + "\" | Panel: \"" + panelTitle + "\""); } },{ text: 'sms message', iconCls: 'email-icon' },{ text: 'push message', iconCls: 'email-icon' }] }] }, renderTo: Ext.getBody() }); });

5. This line demonstrates using the findParentByType method that's available to the MenuItem object passed into the function when the Menu Item is clicked. The findParentByTypemethod is available to all classes that inherit from Ext.Component and allows you to find anycomponent above the component you call it from (in this case Ext.menu.Item) by xtype. Thisexample only uses a Panel with a Toolbar and a few buttons so the following componentsare considered above the Menu Item (Menu, SplitButton, Toolbar and Panel). By passingthe "panel" string to findParentByType it returns a reference to the first Panel it encounterswhich in this case happens to be the only one in the application. Directly after the call tofindParentByType the title property of the Panel is accessed and saved to a local variablenamed panelTitle. That variable is used on the next line to display the title of the Panel in anExt.Msg.alert box.

The last example brought together many of the concepts covered in this guide to show anexample of Toolbars, Buttons and Menus all working together to create interactive interfacecontrols. The code for the last example jumped right into working with events to explorehow easy it is to setup custom functions that execute when different events are fired bycomponents in your application. It also showed a few techniques for accessing Toolbars andPanels from the Buttons and Menus they contain. More in-depth examples of events andaccessing related components will be covered in later guides.

Links• Ext JS Button Examples

• Ext JS Toolbars & Button Menus Examples

• Ext JS Toolbar with Menus

• Ext JS Toolbar Overflow Example