Ext-JS Tutorial
Ext-JS Tutorial
Ext JS Features:
Ext JS is a client side JavaScript application framework to build enterprise applications.
Ext JS supports object-oriented programming concepts using JavaScript which makes easy
application development and maintenance.
Ext JS supports Single Page Application development.
Ext JS includes MVC and MVVM architecture.
Ext JS Data package makes it easy to retrieve or saving of data.
Ext JS includes OOB UI components, containers and layouts.
Ext JS includes drag and drop functionality for UI containers and components.
Ext JS includes localization package that makes it easy to localize application.
Includes OOB themes such as Classic, Gray, Neptune, Crisp, Triton.
Custom Themes using SASS & Compass
Ext JS Versions:
Version Description
Ext JS 4.x Ext JS 4.x framework is used to build desktop
applications. Use Sencha Touch framework to build
mobile and tablet application.
Ext JS 5.x Ext JS 5 is used to build desktop and tablet
applications.
Ext JS 6.x - Current Ext JS 6 is used to buils application for all the
devices from mobile devices to tablets to desktops
while writing less code. It includes two toolkits:
classic and modern. Learn more about it in the Ext
JS 6 section.
Ext JS vs AngularJS:
Ext JS AngularJS
Ext JS is a framework to build web based enterprice AngularJS is a framework that allows you to extend
application using JavaScript. the HTML's syntax.
Ext JS is a per-seat/per-server commercial license AngularJS is an open source framework maintained
framework and open-source under GPL licence by by Google and other community developers.
Sencha.
No need to write single HTML 5 or CSS 3 code. Need to write HTML and CSS code.
Ext JS includes MVC & MVVM architecture. AngularJS support MVC architecture.
Ext JS supports responsive UI. Does not support responsive UI by default. You
need to use Bootstrap or other framework for
responsive design.
Includes OOB UI components such as form, grid, Does not included any OOB UI components.
treeview, dataview etc.
Sencha provides ALM tools for Ext JS. Does not included any ALM tools. You need to use
third party ALM tools.
Includes themes for your entire application such as Does not include any OOB themes.
crisp, triton, neptune, classic, gray etc.
Ext JS History:
Ext JS is a client-side, JavaScript framework for building web applications. In
early 2006, Jack Slocum (jackslocum.com) started working on a set of
extension utilities for the Yahoo User Interface (YUI) library under the name
"yui-ext." Eventually, Jack created an adapter layer, which provided plugin
option for any foundation library to provide utilities such as event handling,
DOM manipulation and animated effects. This unanchored the library from
YUI, and allowed the use of YUI, jQuery, prototype, or a new ext-base
foundation written by Jack. This was version 1 of Ext JS. Current version of
Ext JS is 6.x.
Visit Wikipedia for more information on ExtJS history.
IIS:
If you are using windows platform then you can use IIS by turning on IIS
features. Visit Technet to download and install IIS 7.5 on windows 7.
Once you have installed Apache or IIS, you can verify that it is running by
navigating to localhost in your browser. You should see a startup page
indicating successful installation and running of Apache HTTP Server or IIS
welcome page.
IDE:
You need to write JavaScript code to develop an Ext JS application. So, you
can use any IDE for Sencha development as per your convenience eg.
Aptana, Eclipse, VisualStudio etc.
IDE should satisfy following requirements for the development:
1. It should be able to validate JavaScript code for errors and warnings
2. It should have autocomplete functionality for Ext JS library classes and functions.
3. It should be able to format JavaScript code easily to make Ext JS code readable.
Learn how to setup Aptana, Eclipse and Visual Studio in the next chapter.
8. Click OK.
9. Select all the packages under Spket IDE:
10. Click 'Next'.
11. Accept the License Agreement.
12. Click 'Finish'.
13. This will download and install Spket IDE plugin in Aptana/Eclipse.
14. After installation -> restart Aptana/Eclipse.
Now, you need to configure Spket plugin. Follow the below steps to
configure Spket plugin in Aptana/Eclipse in windows platform:
15. Start Aptana or Eclipse.
16. Go to Windows menu -> Preferences.
17. Expand Spket -> select JavaScript Profiles.
18. Click 'New..'
19. Enter Name as ExtJS and click OK.
20. Now, select ExtJS profile and click 'Add Library'. This opens 'Select Library' popup.
21. Select ExtJS from the drowpdown and click 'OK'.
22. Now, select ExtJS profile and click 'Add Library'.
23. In the Select Library popup, select ExtJS and click OK.
24. Now, select ExtJS child node and click Add Folder and select build folder under Ext JS 6 sdk folder
which you downloaded earlier.
25. This will add all JS files under build folder.
26. Now, set ExtJS profile as Default profile by clicking on Default button.
27. Click OK and restart Aptana or Eclipse.
Now, create new project and JavaScript file and press Ctrl + Space. This
shows autocomplete feature with help as shown below:
This is how you can get autocomplete feature in Aptana or Eclipse.
Select Exclude All, Files and Folders, All Children and enter * in File and
Folder Attributes as shown below:
Now, you get errors and warnings for your JavaScript files only.
Format JavaScript code:
Aptana comes with default code formatter for JavaScript. Press Ctrl + Shift
+ F to format JavaScript code in Aptana.
So, in this way you can setup development environment using Aptana or
Eclipse IDE in Windows platform.
After successful installation it will ask for Sencha userid and password. Enter
it to activate trial version of the plugin. If you have valid license code then
you can enter it to activate it.
Restart Visual Studio after activation.
Now, you can create Ext JS project, Ext JS controller, model, store etc. using
templates.
Let's create Ext JS project in Visual Studio 2013.
Open Visual Studio 2013 and click on File -> New -> Project.. to open
popup as below. Select Sencha under Templates -> Visual C# as below.
As you can see in the above figure, there are two templates for Sencha: 1)
Ext JS Application and Web API 2) Ext JS Workspace and Web API. Here, we
want to create an Ext JS application, so select Ext JS Application and Web
API, enter name and the location of the application and click OK.
This will ask for CMD and SDK location, toolkit and theme. Provide necessary
info and click OK as shown below.
JSLint:
Download and install JSLint for VS2010 from codeplex VS 2012 from
VisualStudiogallery.
JSLint analyzes JavaScript code and gives warnings and errors in JavaScript
code based on the configuration. JSLint is useful to identify missing
semicolon, comma and other basic syntax errors in the JavaScript code.
PrettyJs:
Install PrettyJs to format JavaScript code and make it readable in Visual
Studio 2010.
Ext JS Documentation:
Sencha provides extensive online and offline documentation to learn any of
its products. It includes quick start, guide, API help section.
Online Help:
Go to docs.sencha.com and select the version of Ext JS you are using in your
application.
Offline help:
You can also configure sencha documentation offline on your local machine.
Download zip file for Ext JS, CMD, Sencha Test, Web Application Manager
etc. from here.
After downloading zip file for the help doc, unzip into your preferred folder
and run index.html or configure virtual directory in the local web server. The
following is offline help for Ext JS 6.
Learn about the recommended naming conventions in the next section.
Sencha Cmd:
Sencha Cmd is an ALM tools for Sencha applications. It is a cross-platform
command-line tool which you can use to perform following ALM tasks.
Sencha Cmd Capabilities Description
Code Generation Tool Sencha Cmd can be used to generate application
skeleton, model, view and controller class.
Web Server Sencha Cmd includes lightweight web server which
can be used as a local web server in development.
Build and Deployment Sencha Cmd minifies and creates the build for your
production environment and also deploy it to
production.
Workspance Management Sencha Cmd helps in creating and maintaining
workspance where you can share framework,
packages or custom code between multiple
applications.
MVVM:
In the MVVM architecture, the job of Model and View remains the same as
MVC.
Model is a collection of data fields which persist through the data package.
They can be linked to other models through associations and linked to a data
stream through the use of a proxy.
View is any type of components that output information on to your browser,
i.e. Container, Form, Grid, Chart.
ViewModel is a class that manages data for the specific view.
ViewController: Ext JS 5 introduced ViewController which will be attached
to a specific view and will handle all the events of that view.
You will learn about Ext JS MVVM folder structure in the Ext JS Folder
Structure section. Visit Sencha documentation for the detailed information
on the application architecture.
As you can see in the above figure, path of the Ext JS 6 sdk is
"D:\ExtJS\ExtJS-SDK\ext-6.0.1". The application name would be
"MyExtJSApp" and the path where an application will be generated is
"C:\ExtJS\MyExtJSApp". It will take some time in executing the above
command.
Now, open browser (preferably Google Chrome) and enter the URL
https://localhost:8008. This will display first default Ext JS 6 application as
shown below.
Setup Web Server:
You can also use your local web server instead of Sencha Cmd. Here, we will
setup IIS on windows platform.
First, open IIS manager by searching for "inetmgr" and click on it. IIS
Manager will look like below.
Now, we need to add web site for our Ext JS app. So, right click on Sites and
click Add Web Site.. This will open Add Web Site popup as shown below.
In the Add Web Site popup, enter Site name, and select physical path where
you have generated Ext JS application. Also, enter any unused port number
and click OK. This will add new website as shown below.
Now, open browser (preferably Google Chrome) and enter the URL
http://localhost:8007. This will display first default Ext JS 6 application as
shown below.
Thus, you can create and run your first default Ext JS 6 application.
Let's understand Ext JS folder structure in the next section.
Ext JS Application Structure:
In the previous section, we created our first Ext JS application using Sencha
Cmd. You have seen that it created files and folders to get started. Here,
you will learn about important files and folders for an Ext JS Application.
Sencha Cmd created following files and folders while generating sample Ext
JS application. Every Ext JS applications follow the same folder structure.
app
The app folder is important folder that includes all the custom files and
folders of your application as shown below.
As you can see in the above figure, app folder contains model, store and
view folder. You can create all your model classes in model folder, store
classes in store folder. The view folder can contains separate folders for
each views you create for your application. For example, the above view
folder contains 'main' folder which includes MainController.js and
MainModel.js which is ViewController and ViewModel respectively. The actual
views will be created either in classic or modern folders. You will learn about
it later in this section.
The app folder also contains Application.js file which contains global settings
for your application such as app name, shared stores, models etc. Every Ext
JS application starts with an instance of the Application Class. This class is
intended to be launch-able by app.js as well as instantiable for testing.
build
The build folder contains markup page, JavaScript code and themes when
you build your application using Sencha Cmd command sencha app build.
classic
Ext JS includes two types of toolkit: classic and modern. The classic folder
contains all your views that will be rendered for desktop browser or tablet.
The following figure shows the classic folder that includes views for the
desktop and tablets.
As you can see in the above figure, folders inside classic folders follow the
same structure as view folder under app folder. So, app -> view -> main
contains ViewController and ViewModel which will be shared between classic
and modern toolkit and classic -> view -> main contains views to be
rendered in desktop and tablets.
ext
The ext is a sdk folder which contains all the necessary files and folders for
Ext JS 6 framework.
modern
As mentioned above, Ext JS includes classic and modern toolkits. So,
modern folder contains views for the mobile devices. It will includes the
same folder structure as classic if you build universe application for all the
devices.
overrides
The overrides folder includes all your code that has overridden default
behaviour of Ext JS. For example, if you want to override Ajax functionality
then you need to create a class inside overrides folder so that Sencha Cmd
will build it automatically.
packages
The packages folder includes your local or third party packages which you
can share with Sencha community. This allows you to share your features
with other application as well as Sencha community.
resources
The resources folder can contains resource files such as custom images, css
etc. for your application.
sass
Ext JS uses sass folder for its themes files.
app.js
The app.js is a gateway to your Ext JS application. It creates and launches
an instance of Application.js in app.js file. It also can be used to designate a
container class using mainView config so that we can use any class as
Viewport.
app.json
Ext Js uses Microloader to load application resources described in the
app.json file. This replaces the need to add them to index.html. Sencha Cmd
uses app.json to build an application. With app.json, all of the application
meta-data exists in a single location.
build.xml
This file is used by Sencha cmd to build an application when you execute
sencha app buildcommand. It also allows you to avoid changes to ./sencha
folder when you want to add some extra functionality to your build process.
index.html
The index.html is a root HTML file of Ext JS application. The following is the
content of index.html file.
<!DOCTYPE HTML><html manifest=""><head> <meta http-equiv="X-UA-Compatible"
content="IE=edge"> <meta charset="UTF-8"> <meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-
scalable=no"> <title>MyExtJSApp</title> <script
type="text/javascript"> var Ext = Ext || {}; // Ext namespace won't be
defined yet... // This function is called by the Microloader after it
has performed basic // device detection. The results are provided in
the "tags" object. You can // use these tags here or even add custom
tags. These can be used by platform // filters in your manifest or by
platformConfig expressions in your app. // Ext.beforeLoad =
function (tags) { var s = location.search, // the query string
(ex "?foo=1&bar") profile; // For testing look for
"?classic" or "?modern" in the URL to override // device detection
default. // if (s.match(/\bclassic\b/)) {
profile = 'classic'; } else if (s.match(/\bmodern\b/))
{ profile = 'modern'; } else {
profile = tags.desktop ? 'classic' : 'modern'; //profile =
tags.phone ? 'modern' : 'classic'; } Ext.manifest =
profile; // this name must match a build profile name // This
function is called once the manifest is available but before //
any data is pulled from it. // //return function
(manifest) { // peek at / modify the manifest object
//}; }; </script> <!-- The line below must be kept
intact for Sencha Cmd to build your application --> <script
id="microloader" data-app="fec7a5cc-a11f-4421-b84d-127e09d0bdf7"
type="text/javascript"
src="bootstrap.js"></script></head><body></body></html>
As you can see above, it includes microloader so that Sencha Cmd can build
your application. Do not remove or change this.
Syntax:
Ext.define((String) className, (Object) classMembers, (Optional Function)
onClassCreatedCallback);
Parameters:
className is the full class name in dot-namespaced format
classMembers is an object represents a collection of class members in key-
value pairs (Javascript object literals)
onClassCreatedCallback is an optional function callback to be invoked when
all dependencies of this class are ready, and the class itself is fully created.
Ext.define() performs the following operations:
32. Detects and creates new namespaces if required.
33. Extends an existing class.
34. Verifies if the class being extended has been defined, if not, it will defer the creation of the new class
until the class used for extending is available.
35. Returns Ext.Base object.
Note: Ext.Base is root of all classes created with Ext.define. All the classes
in Ext JS inherit from Ext.Base
Ext.define('Student', { name : 'unnamed', getName : function(){
return "Student name is" + this.name; }}, function(){ alert('Student
object created');});
Above example defines Student class with one member variable 'name' and
one method getName().
As per the syntax of Ext.define, the first parameter 'Student' is class name.
The second parameter is a JavaScript object which contains name and
getName(), and the third parameter (optional) is callback function which will
be called after 'Student' class is created.
So this way you can create custom class in Ext JS.
Define Constructor:
To define a custom class with constructor, add function name constructor as
a class member:
Ext.define('Student', { name : 'unnamed', getName : function(){
return 'Student name is ' + this.name; }, constructor :
function(studentName){ if(studentName) this.name =
studentName; }});
Note: Most of the time you will have to extend Ext JS components in your
application to use default functionality of the component and add custom
functionality. Mixins:
Mixins introduced since Ext JS 4. Mixins allows us to use functions of one
class as a function of another class without inheritance.
Mixins can be defined using mixins keyword and specify value as a JSON
object where name of a property should be name of the method which you
want to use and the value of a property will be name of the class where the
method is defined.
Consider the following example.
Ext.define('Person', { name: 'Unknown', constructor:
function(name) { if (name) { this.name = name;
} }, getName: function() { alert("My name is " +
this.name); }, eat: function(foodType) { alert( "I'm
eating " + foodType); }});Ext.define('Student', { schoolName:
'', constructor: function(schoolName) { this.schoolName =
schoolName || 'Unknown' }, mixins: { eat: 'Person' },
getSchoolName: function() { alert("I am a student of " +
this.schoolName); }});var studentObj = new Ext.create('Student',
'XYZ');studentObj.eat('Sandwich');
In the above example, Student class defines mixins and specify 'eat' as a
property name and 'Person' as a value where eat() method is defined. So
now you can call studentObj.eat()method as if it is defined in the Student
class.
Config:
Ext JS has a feature called config. The config allows you to declare public
properties with default values which will be completely encapsulated from
other class members. Properties which are declared via config, will have
get() and set() method automatically if class does not have these methods
already defined.
The config properties can be defined using config keyword with JSON object
as a value where you can define properties. Consider the following example.
Ext.define('Student', { config : { name : 'unnamed',
schoolName : 'Unknown' }, constructor : function(config){
this.initConfig(config); }});
In the above example, Student class includes two config properties: name
and schoolName with the default value 'unknown'. In the constructor, we call
this.initConfig(config). This will create get and set methods for all the config
properties. We must call this.initConfig(config)in the constructor in order to
initialize getters and setters. The get method returns a value of a config
property and set method is used to assign a new value to a config property.
The name of the get method will start from get and suffix with property
name like get<config property name>() and the same way set method will
be named as set<config property name>(). The suffix in get and set method
names will start from capital character. So, get and set method names for
the above name and schoolName config properties will be getName(),
setName(), getSchoolName() and setSchoolName().
The following example demonstrates accessing get and set method of the
above Student class.
Ext.define('Student', { config : { name : 'unnamed',
schoolName : 'Unknown' }, constructor : function(config){
this.initConfig(config); }});var newStudent = Ext.create('Student',
{ name: 'XYZ', schoolName: 'ABC School' });newStudent.getName();//output:
XYZnewStudent.getSchoolName();//output: ABC
SchoolnewStudent.setName('John');newStudent.setSchoolName('New
School');newStudent.getName();//output:
JohnnewStudent.getSchoolName();//output: New School
Try it on https://fiddle.sencha.com/#fiddle/3l2
As you can see in the above example, we have not defined getName(),
setName() and getSchoolName(), setSchoolName() methods in Student
object. It was automatically created for config properties by Ext JS API.
Please note that you cannot assign config property value directly same as
normal class property. You must use set method to assign a value to config
property. For example, the following is NOT valid. It does not assign a value
to name property instead it creates another property name on the instance.
newStudent.name = 'Steve'; //Not valid.newStudent.setName('Steve');//Valid
Custom Setters:
You have seen get and set methods are created for config property
automatically. But, how to add extra logic before or after we assign a value
to config property because get and set methods are managed internally. The
answer is custom setters. Custom setters allow you to add extra logic to
your setters. There are two custom setters: apply and update.
The apply() method for config property allows us to add some extra logic
before it assigns the value to config property. The name of apply method
must start with apply with config property name as suffix in CamelCase.
The update() method executes after the configuration property value has
been assigned. The name of update method must start with update with
config property name as suffix in CamelCase. It has two parameters,
newValue and oldValue. If you include apply and update method for a
particular property then first apply will get called and then update method
will get called.
Consider the following example.
Ext.define('Student',{ config : { name : 'unnamed',
schoolName : 'Unknown' }, constructor : function(config){
this.initConfig(config); }, applyName : function(name){
return Ext.String.capitalize(name); }, updateName :
function(newValue, oldValue){ alert('New value: ' + newValue + ', Old
value: ' + oldValue); }});var newStudent = Ext.create('Student', {name :
'xyz', schoolName : 'ABC School'});newStudent.setName('john');
In the above example, we have defined applyName() method for the name
config property which will capitalize the value of name property. The
applyName() method will be called whenever you set the value of name
config using setName() method. Thus, you can make sure that the value of
name will always be capital even if user set it in small letters.
The updateName() method in the above example executes after assigning
config property value and that's why it includes two parameters. First
parameter is for new value and second parameter is for old value.
Try it on https://fiddle.sencha.com/#fiddle/1icd
Custom Events in Ext JS:
Ext JS allows us to define custom events in class using Ext.mixin.Observable
mixin. Ext.mixin.Observable provides common interface for publishing
events in Ext JS 5 & 6.
The following example demonstrates how you can publish an event using
mixins whenever student name changes.
Ext.define('Student', { config : { name : '' }, mixins :
{ observable : 'Ext.util.Observable' }, constructor :
function(config){ this.mixins.observable.constructor.call(this,
config); }, updateName : function(newValue, oldValue){
this.fireEvent('studentNameChanged', newValue); }});var newStudent =
Ext.create('Student', { name: 'xyz' });newStudent.on('studentNameChanged',
function(name){ alert('student Name ' + name + 'has been
Chaged.');});newStudent.setName('John');
Ext.dom.Element
Ext JS includes Ext.dom.Element class that wraps the actual HTML DOM
element. Ext.dom.Element class includes methods to modify DOM element
and also manages cross-browser issues. Ext.get() and Ext.fly() method
returns an object of Ext.dom.Element.
Method Description
Ext.get() Returns an object of Ext.dom.Element for the
specified id of existing DOM element.
Ext.fly() Performs the same action as Ext.get(). It is designed
to manipulate DOM element as a single statement
and does not store a reference in a memory.
Try it on https://fiddle.sencha.com/#fiddle/s7q
In the above example, Ext.get() method returns an object of
Ext.dom.Element for the input type whose id is "txtFirstName". You can then
use various methods of Ext.dom.Element to manipulate DOM element, for
example, set() method is used in the above example to set the input value.
In the same way, Ext.fly() method is used to get the reference of DOM
element and manipulate it in the same statement.
Note: When you do not need to perform multiple operations on the DOM
element, the Ext.fly() function is the more efficient way to manipulate a
DOM element. It is designed to operate more efficiently and uses less
memory.
In the next section, learn how to create or manipulate composite elements.
Try it on https://fiddle.sencha.com/#fiddle/s7r
In the above example, Ext.select() returns Ext.dom.CompositeElement that
includes all the input elements. You can then manipulate all the elements in
a single statement. The set() method sets the style attribute of all the
selected elements.
The same way you can select other elements by passing different CSS
selectors into select() method and use various methods of
Ext.dom.CompositeElement. Visit sencha docs to know all the methods of
Ext.dom.CompositeElement.
DomHelper:
Ext.dom.Helper class allows us to add new DOM elements, modify or remove
existing DOM elements in an HTML document.
DomHelper class uses JSON based syntax with following special attributes to
create new DOM elements.
Attribute Description
Tag HTML tag of the element to create
Children or cn an array of the same type of element definition of
tags
Cls The class attribute of an element
Html innerHTML value of the element
Id The id of the element
Ext JS Component:
An Ext JS application UI is made up of one or more widgets called
Components. Component is a group of DOM elements with complex
functionality. All the Ext JS components inherit from Ext.Component class.
ExtJS provides different types of components out of the box with complex
functionalities, which you can use in your application such as Viewport,
panel, container, grid, textfield, combobox, numberfield etc.
Ext JS UI components are derived from the Ext.Component class, which in-
turn is derived from the Ext.Base class.
The following example demonstrates creating a simple component.
Ext.onReady(function () { Ext.create('Ext.Component',
{ id:'myComponent', renderTo: Ext.getBody(), html:'Hello
World!' });});
Try it on https://fiddle.sencha.com/#fiddle/s7t
In the above example, we have created a simple component using
Ext.create() method. It will be rendered to the document body and will
display a simple string 'Hello World!'.
All the components in Ext JS are registered with Ext.ComponentManager
class on creation, so that it can be accessed by id using Ext.getCmp()
method. The above component can be accessed using
Ext.getCmp('myComponent').
Ext JS 6 UI Components:
Ext JS 6 contains following UI components out-of the box.
Component Name Class Name xtype
ComboBox Ext.form.field.ComboBox combobox or combo
Radio Button Ext.form.field.Radio radio or radiofield
Checkbox Ext.form.field.Checkbox checkbox or checkboxfield
TextField Ext.form.field.Text textfield
Label Ext.form.Label label
Button Ext.button.Button button
DateField Ext.form.field.Date datefield
File Upload Ext.form.field.File filefield, fileuploadfield
Hidden Field Ext.form.field.Hidden hidden
Number Field Ext.form.field.Number numberfield
Spinner Ext.form.field.Spinner spinnerfield
Text Area Ext.form.field.TextArea textarea
Time Field Ext.form.field.Time timefield
Trigger Ext.form.field.Trigger triggerfield, trigger
Chart Ext.chart.CartesianChart chart
Html Editor Ext.form.field.HtmlEditor htmleditor
xtype: Every Component has a symbolic name called 'xtype'. For example
Ext.panel.Panel has xtype : 'panel'.
Visit Sencha documentation to know how each components look like and
work.
Ext JS Containers:
Ext JS includes components that can contain other components are called
container. You can add, insert or remove components from the container
and also arrange child components using different layouts.
Ext.container.Container is a base class for all the containers in Ext JS.
Try it on https://fiddle.sencha.com/#fiddle/s7u
In the above example, comp3 and comp4 are added into container1 using
items config property whereas container2 includes comp1 and comp2. The
container1 also adds container2 using add() method. The above example
would be resulted as below.
Note: Containers are same in Ext JS 4.x, 5.x and 6.x. The only difference is
that the incremental version provides more config properties and methods.
Ext JS 6 Containers:
The following table lists all important containers in Ext JS 6.
Class Name xtype Description
Ext.container.Viewport viewport ViewPort is a specialized
container representing the
viewable application area (the
browser viewport). Generally
there is a single ViewPort in an
Ext JS application which will
define the application's main
areas like north, west, south, east
and center.
container container Container is lightweight container
which provides basic functionality
of containing items, namely
adding, inserting and removing
items. So use this container when
you just want to add other
components and arrange them.
Ext.panel.Panel panel Panel is a special type of
container that has specific
functionality and components.
Each panel has header, tool,
body, toolbar components. So
use Panel when you want specific
user interface with header,
toolbar and body part. Do not use
it if you do not want these
features in panel, use container
instead.
Ext.form.Panel form Ext.form.Panel provides standard
containers for form. Use it when
you want standard application
form kind of user interface.
Ext.form.FieldContainer fieldcontainer FieldContainer implements
labelable mixins so that it can be
rendered with label and error
message around every sub-item
component. You can use
fieldcontainer in the form to
arrange inner fields.
Ext.form.FieldSet fieldset Fieldset is a container for group
of fields in an Ext.form.Panel.
Ext.grid.Panel grid Grid displays large amount of
tabular data with sorting, filtering
and other functionality.
Ext.container.ButtonGroup buttongroup ButtonGroup provides a
container for arranging a group of
related Buttons in a tabular
manner.
Ext.tab.Panel tabpanel Ext.tab.Panel is a basic tab
container. Use it when you want
tab or wizard in your user
interface.
Ext.tree.Panel treepanel TreePanel provides tree-
structured UI representation of
tree-structured data.
Ext.menu.Menu menu Menu is a container to which you
can add Menu Items.
Ext.toolbar.Toolbar toolbar Toolbar is a container for toolbar
buttons, text, fill, item etc.
Try it on https://fiddle.sencha.com/#fiddle/s7v
Visit Layouts Example for more practical information on layouts.
ComponentQuery:
Ext JS provides singleton class Ext.ComponentQuery to search for
components in the HTML page with a syntax similar to a CSS selector.
The Ext.ComponentQuery class provides different methods to perform
different tasks e.g. adding properties in a component class, creating an
object of a component, get config properties of a component, query to
search components etc..
Components can be retrieved in the following ways.
Query Type Description
xtype Components can be retrieved by their xtype.
itemId or id Components can be retrieved by their id or itemId.
The id must be prefixed with #.
Attributes Components can be retrieved by their attributes or
config properties.
descendant Components can be retrieved by the descendant.
Direct child Components can be retrieved by the direct child
relationship.
Parent Ext.ComponentQuery.query('textfield ^
panel'); // retrieves all the panels which is parent
of a textfield.
Try it on https://fiddle.sencha.com/#fiddle/sb6
In the above example, the first query 'container datefield' searches all the
datefield components inside any container in a document.
The second query 'panel > datefield' searches for all the datefields which is
direct child of panel.
The third query '#myContainer #email' searches for the component whose id
is 'email' inside a container whose id is 'myContainer'.
Ext JS Viewport:
Viewport in Ext JS is a specialized container representing the viewable
application area in the browser. There can be only one viewport in ExtJS 4
single page application.
The Viewport renders itself to the document body, and automatically resizes
itself to the size of the browser viewport and manages window resizing.
Let's create a viewport in an Ext JS application.
First, create a app.js as shown below.
Ext.application({ name: 'School', mainView: 'School.view.Viewport'});
In the above app.js, mainView config indicates the initial view to render.
Here, it is a view class School.view.Viewport. We will use classic toolkit for our
sample app. So, create a classicfolder and a view folder inside classic
folder.
In the view folder, create Viewport.js and define Schoo.view.Viewport class as
shown below.
Ext.define('School.view.Viewport', { extend: 'Ext.container.Viewport',
alias: 'widget.StudentViewport', requires:
['Ext.menu.Menu','School.view.ViewportController'], controller:'viewport',
config: {}, constructor: function(config) { return
this.callParent(arguments); }, initComponent: function()
{ Ext.apply(this, { id: 'StudentViewportID',
title: 'Student Information', layout: {
type: 'border' }, items: [{ region:
'north', border: false, margins: '0 0 5 0',
items: [{ xtype: 'container', html:
'<h1 class="x-panel-header">extjs-tutorial.com</h1>' }, {
xtype: 'toolbar', itemId: 'schoolToolbar',
enableOverflow: true, items:
[{ xtype: 'button', // default
for Toolbars text: 'Add Tab',
itemId: 'btnAddtabs', listeners: {
click: 'onAddTab' } }, {
xtype: 'button', // default for Toolbars
text: 'Add Window', itemId: 'btnAddwindow',
listeners: { click: 'onAddWindow'
} },
{ xtype: 'splitbutton', text:
'Split Button' },
'->', { xtype: 'textfield',
name: 'field1', emptyText: 'enter search term'
}, '-', 'text 1',
{ xtype: 'tbspacer' },
'text 2', { xtype: 'tbspacer',
width: 50 }, 'text
3'] }] }, { region: 'west',
collapsible: true, title: 'Navigation', width:
150, split: true, items:
[{ xtype: 'menu', width: 150,
plain: true, floating: false,
showSeparator: true, items:
[{ text: 'Menu item 1' }, {
xtype: 'menuseparator' }, { text:
'Menu item 2' }, { xtype:
'menuseparator' }, { text: 'Menu
item 3' }] }] }, {
region: 'south', title: 'South Panel',
collapsible: true, html: 'Information goes here',
split: true, height: 100, minHeight: 100
}, { region: 'east', title: 'East Panel',
split: true, width: 150 }, { region:
'center', xtype: 'tabpanel', activeTab: 0,
items: [{ title: 'Default Tab', html:
'The first tab\'s content. Others may be added dynamically' },
{ title: 'Second Tab', html: 'The
second tab\'s content. Others may be added dynamically' }]
}] }); this.callParent(arguments); }});
Ext.define('School.view.ViewportController', { extend:
'Ext.app.ViewController', alias: 'controller.viewport', onAddWindow:
function(sender, record) { Ext.Msg.alert('Add Window', 'Add a new
window here.'); }, onAddTab: function(choice)
{ Ext.Msg.alert('Add Tab', 'Add a new tab here.'); }});
Try it on https://fiddle.sencha.com/#fiddle/1itp
Visit Sencha documentation for more information on viewport.
MessageBox:
You can display many types of messageboxes in Ext JS.
Ext.window.MessageBox is the main class for creating messagebox in Ext JS.
Ext.MessageBox or Ext.Msg is a singleton instance of Ext.window.MessageBox.
You don't have to create an object of Ext.window.MessageBox to show
messagebox all the time.
Unlike a regular JavaScript alert (which halts the browser execution),
showing a message box using Ext.Msg will not cause the code to stop. If you
have code that should run after user's action from the message box, you
must specify a callback function.
You can display four types of message boxes:
Alert: Displays a standard read-only message box with an OK button.
Confirm: Displays a confirmation message box with Yes and No buttons.
Prompt: Displays a message box with OK and Cancel buttons prompting the
user to enter some text (similar to JavaScript's prompt). It can be a single-
line or multi-line textbox.
Custom: Customized message box style.
Let's see an example of each type:
Singleton Alert:
You can display alert using 'Ext.Msg', which is a short form of singleton class
‘Ext.MessageBox'.
Ext.Msg.alert('Status', 'This is Ext JS message box.');
Try it on https://fiddle.sencha.com/#fiddle/1k5s
Note: If you have two consecutive alert messages using ‘Ext.Msg', then the
latest alert message will be displayed because Ext.Msg is a singleton class.
Ext.Msg.alert('Status', 'This is first Ext JS message
box.');Ext.Msg.alert('Status', 'This is second Ext JS message box.');
Try it on https://fiddle.sencha.com/#fiddle/1k5u
In the above example, you will see only one message box with the message
'This is second Ext JS message box.'
You may also create an object of Ext.window.MessageBox and call alert
method like below:
var msg = Ext.create('Ext.window.MessageBox');msg.alert('Status', 'This is
Ext JS message box.');
Try it on https://fiddle.sencha.com/#fiddle/1k5v
Confirm:
Confirm message box displays message with Yes and No buttons. You can
also capture users click event for further process.
Ext.Msg.confirm("Confirmation", "Do you want to Save changes?",
function(btnText){ if(btnText === "no")
{ Ext.Msg.alert("Alert", "You have confirmed 'No'.");
} else if(btnText === "yes")
{ Ext.Msg.alert("Alert", "You have confirmed 'Yes'.");
} }, this);
Try it on https://fiddle.sencha.com/#fiddle/1k60
Prompt:
Prompt displays a message box with OK and Cancel buttons prompting the
user to enter some text.
Ext.Msg.prompt("Ext JS Tutorials", "Please enter your Sencha Id:",
function(btnText, sInput){ if(btnText === 'ok'){
Ext.Msg.alert("Status", "You entered:" + sInput); }
}, this);
Try it on https://fiddle.sencha.com/#fiddle/1k61
Try it on https://fiddle.sencha.com/#fiddle/3kt
You can also use Ext.MessageBox to show automatic progress bar as below:
Ext.MessageBox.show({ msg : 'Saving changes, please wait...',
progressText : 'Saving...', width : 300, wait : true,
waitConfig : { duration : 10000, increment :
15, text : 'Saving...', scope : this, fn :
function(){ Ext.MessageBox.hide();
Ext.Msg.alert('Status', 'Saved successfully!'); } } });
Try it on https://fiddle.sencha.com/#fiddle/3ku
Please visit Sencha documentation for more information on progress bar.