0% found this document useful (0 votes)
186 views

Ext-JS Tutorial

Ext JS is a JavaScript framework for building data-intensive web applications. It allows developers to create enterprise applications using JavaScript with pre-built UI components and layouts without writing HTML or CSS code. Ext JS supports features like responsive design, MVC architecture, and includes tools for localization and theming. The current version is Ext JS 6, which can be used to build applications for desktops, tablets, and mobile devices.

Uploaded by

javatraining
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
186 views

Ext-JS Tutorial

Ext JS is a JavaScript framework for building data-intensive web applications. It allows developers to create enterprise applications using JavaScript with pre-built UI components and layouts without writing HTML or CSS code. Ext JS supports features like responsive design, MVC architecture, and includes tools for localization and theming. The current version is Ext JS 6, which can be used to build applications for desktops, tablets, and mobile devices.

Uploaded by

javatraining
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

Ext JS Introduction:

Ext JS is the most powerful JavaScript based application development


platform. It allows you to create data-intensive HTML 5 applications using
JavaScript with unparalleled cross-browser compatibility.
Ext JS framework allows us to build enterprise application with unified user
experience using JavaScript without writing any HTML 5 or CSS code. It
includes built-in themes and UI components out of the box which minimize
development time and increases the productivity.
Ext JS is a product of Sencha. It offers following products.
Ext JS is a framework for web applications based on JavaScript and Html5.
Sencha Touch is a high-performance HTML5 mobile application framework.
Sencha GXT is the fastest, most powerful way to create rich web-based
applications using Java.
Please visit Sencha.com for more information on Sencha products and tools.

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.

Setup Ext JS Development Environment:


Before starting with Sencha Ext JS, you need to setup a development
environment for it. There are three things required for Ext JS application
development: Sencha SDK, web server and IDE to write JavaScript code.
Ext JS SDK:
Ext JS is a commercial product. It means you have to buy it in order to
develop any product which is intended for sale. However, if you want to use
Ext JS for learning purpose or to build open source product then you can
download GPL sdk.
Download latest version of Ext JS SDK (which is Ext JS 6 as of this writing)
from https://www.sencha.com/legal/gpl/. Provide your mail id and
acknowledge terms and condition to download it free.
Ext JS 6 SDK includes following folders.

Ext JS 5 SDK includes following folders.


Web server:
Ext JS is used to build web based enterprise applications. So, you need to
install a web server on your local machine. You may use any web server of
your choice. However, some IDEs have built-in local web server so you can
use that too.

Apache HTTP server:


 Visit apache.org to install apache on windows.
 Mac OS X comes with a built-in apache installation which you can enable by navigating to "System
Preferences > Sharing" and checking the box next to "Web Sharing"

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.

Setup Aptana Studio/Eclipse for Ext JS


Development:
In this chapter, we are going to setup Aptana IDE for Ext JS 6 development.
You can follow the same thing to setup Eclipse IDE also.
Aptana is a powerful open-source web development IDE. Please download
and install Aptana Studio 3.
Now, you need to install Spket IDE plugin from spket.com. Spket is a
powerful toolkit for JavaScript and XML development. It enables
autocomplete feature for Ext JS as soon as you install and configure Spket
IDE plugin in Aptana or Eclipse.

Install Spket plugin in Aptana or Eclipse:


4. Open Aptana/Eclipse.
5. Go to Help menu -> 'Install New Software..'
6. It will open a popup window as shown below:
7. Click 'Add' and enter name 'Spket' and Location ‘http://www.agpad.com/update/’.

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.

JavaScript Syntax errors and warnings:


Aptana or Eclipse comes with JSLint and JavaScript Syntax validators.
However, JSLint validator is disabled by default. To enable it,
28. Go to Windows -> Preferences.
29. Expand Aptana Studio node.
30. Select Validation. There you will see JSLint Validator:
31. Select JSLint validator and click OK.
Now the Problems window displays JavaScript errors and warnings for your
project. However, you need to exclude extjs sdk folder because JSLint shows
errors and warnings for many sdk JS files.
To exclude it, right click on sdk folder in Project explorer -> select Properties
-> select Resource Filters under Resource node and click 'Add':

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.

Setup Visual Studio for Ext JS Development


You can also use Visual Studio if you are coming from Microsoft world.
Download Visual Studio from visualstudio.com.

Setup Visual Studio 2013:


Sencha provides plugin for Visual Studio 2013 and 2015 Enterprise,
Professional, Ultimate, Premium, or Community editions. It is available to
Ext JS Pro and Premium customers at no extra charge. If you use EXT JS
SDK GPL license then it will be available for 30 days trail.

Install Sencha Plugin:


Here, we will install Sencha plugin in Visual Studio 2013 Community Edition.
Open Visual Studio 2013 and go to Tools -> Extensions and Updates.. to
open following popup. Select Online section in the left pane.
Now, search for sencha at top right corner. This will list Sencha Visual Studio
Extension plugin as shown below.
As you can see above, click on Download button to download it. After
downloading completes it will ask for installation as shown below. Click on
Install to install this plugin into Visual Studio.

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.

It will create Ext JS project as shown below.


As you can see in the above figure, Sencha folder is hidden. Unload the
project and reload to make it visible as shown below.
Now, you can achieve auto code completion and other features.

Visit Sencha Docs for more information.


Setup Visual Studio 2010/2012:
Sencha plugin is not supported in Visual Studio 2010/2012. So, you need to
install following plugins manually in Visual Studio for better JavaScript
coding experience:

Jscript editor extension:


Install Javascript editor extension for VS2010. It is useful for brace
matching, outlining etc. for easy JavaScript development. VS2012 includes it
by default.

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.

Install Sencha Cmd:


Before you install Sencha Cmd, install Ruby to compile themes and
applications from rubyinstaller.org.
Now, download and install the Sencha Cmd for the same version as your Ext
JS framework. We will use Ext JS 6 so download and install Sencha Cmd 6
from here.
Once you install it, verify the installation by writing Sencha in the command
line tool as shown below in Windows platform.

Sencha Cmd Commands:


You can execute various commands in Sencha Cmd to execute different
tasks. The following is command syntax.
sencha [category] [command] [options...] [arguments...]

Sencha includes following categoris of commands.


 App
 Package
 Theme
 Generate
 Compile
 Repository

For example, the following command is used to generate Ext JS application


skeleton.
sencha -sdk pathToSenchaSDK generate app appName pathToAppFolder

You can also get the help on any module or action.


sencha help [module] [action]
We will use Sencha Cmd in these tutorials to perform various tasks. Visit
Sencha documentation for more information on Sencha Cmd.

Ext JS MVVM Architecture:


ExtJS 4.x was based on MVC (Model-View-Controller) architecture. Ext JS
supports MVVM (Model-View-ViewModel) architecture since Ext JS 5.

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.

Create First Ext JS Application:


In this section, we will create first Ext JS 6 application using Sencha Cmd.
As you learned in the previous section that Sencha Cmd can be used to
generate an Ext JS application skeleton to get started on it quickly.
Let's generate Ext JS 6 application in Windows platform using Sencha Cmd.
Make sure that you have installed Sencha Cmd and downloaded GPL Ext JS
SDK.
Open Windows command prompt in admin mode as shown below.
Now, navigate to the path where you want to generate an application.

Now, write following generate command and press Enter.


sencha -sdk /path/to/extjs/framework generate app AppName path/to/app

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.

After successful execution, it will generate following folders and files.


Thus, we have created our Ext JS application's skeleton.

Run Ext JS Web Application:


Now, to run our sample Ext JS application, we need to setup a web server.
Sencha Cmd includes light weight local web server. So we can run it using
Sencha Cmd.
Open command prompt in windows and navigate to the directory where you
have your Ext JS application as shown below.
Now, enter Sencha web –port xxxx start command as shown below. Use
any unused port number.

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.

Let's understand the significance of each files and folders.

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.

bootstrap.css, bootstrap.js, and bootstrap.json


Ext JS supports dependency management using requires feature. These
bootstrap files contains the information about the minimum CSS and
JavaScript code needed to run your application using dependency
management.

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.

classic.json and modern.json


The classic.json file includes paths for all your views and other resources
that will be used to render your application in desktop and tablet devices.
The modern.json file includes paths for resource files for mobile devices.

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.

ExtJS Naming Convention:


Ext JS is a JavaScript framework. Therefore, you should follow most of the
JavaScript naming conventions.
Sencha suggests following naming conventions for Ext JS application:
Convention for Description Example
Class Class name should be in MyCustomClass
CamelCase
Class name should contain Base64
alphanumeric characters.
Numbers are permitted if it
belongs to a technical term.
Do not use underscores, hyphens,
or any other non-alphanumeric
characters.
Class name should be with at TopLevelNamespace.MyClassNa
least one unique namespace me
separated by dot (.).
Classes that are not distributed
by Sencha should never use Ext
as the top-level namespace.
The top-level namespaces and TopNamespace.middnamespace.
the actual class names should be CustomClass
in CamelCase, everything else
should be in lower-case.
Source File The names of the classes map Ext.util.Observable is stored in
directly to the file paths in which path/to/src/Ext/util/Observable.j
they are stored. As a result, there s
must only be one class per file. MyTopLevelNamespace.util.JsonT
oXml is tored in
path/to/src/MyTopLevelNamespa
ce/util/ JsonToXml.js
Methods Method should always be in encodeUsingMd5(), getHtml()
camelCase.
Variables Variable should always be in var isGoodName
camelCase. var base64Encoder
Constant variable should be in var SALARY = 1000
upper-case
Private variable should start with var _privateVariable
underscore ‘_’
Properties Properties should always be in Ext.MessageBox.YES = "Yes"
camelCase. Static properties
should bein upper-case.

Also, visit javascript.crockford.com for JavaScript coding conventions used in


JSLint.

Ext JS Class System:


Ext JS ships with more than 300 classes. So before going into further detail,
let's understand basic class system of Ext JS 4, 5 and 6.
Ext is a global singleton class and also a top level namespace which you
would use almost everywhere in Ext JS. Ext class has 78 methods and 59
properties. Some of the important methods that will be used frequently such
as Ext.application(), Ext.apply(), Ext.create(), Ext.define(), Ext.getCmp(),
Ext.override() etc.
All the classes namespace in Ext JS API starts from 'Ext'. Visit
doc.sencha.com for more information on Ext class in Ext JS 6.x.
The following table lists some of the important classes in Ext JS API:
Class Description
Ext The Ext namespace (global object) encapsulates all
classes, singletons, and utility methods provided by
Sencha libraries.
Ext.Base The root of all classes created with Ext.define.
Ext.Base is the building block of all Ext classes. All
classes in Ext inherit from Ext.Base. All prototype
and static members of this class are inherited by all
other classes.
Ext.ClassManager Ext.ClassManager manages all classes and handles
mapping from string class name to actual class
objects throughout the whole framework.
Ext.Loader Ext.Loader is the heart of the new dynamic
dependency loading capability in Ext JS 4+. It is most
commonly used via the Ext.require shorthand.

Visit Sencha doc for more information on Ext JS class system.

Define New Class:


Use Ext.define() method to define new custom class in Ext JS 4, 5 & 6.

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.

Create an Object of a Class:


JavaScript allows us to create an object using new keyword. However,
Sencha recommends to use Ext.create() method to create an object of a
class which is created using Ext.define() method.
The following example demonstrates creating an object of the Student class
and calling getName() method.
var studentObj = Ext.create('Student');studentObj.getName();

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; }});

Now you can create an object by passing parameter to the constructor:


var studentObj = Ext.create('Student','XYZ');//orvar studentObj = new
Student('XYZ');studentObj.getName()

;//output: Student name is XYZ

Declare Private Members in Class:


Use JavaScript closure to create private members of the class as below:
Ext.define('Student', function(){ var name = 'unnamed'; return {
constructor : function(name){ this.name = name; },
getName : function(){ alert('Student name is' + this.name);
} };});//create an object of Student classvar studentObj =
Ext.create('Student','XYZ');studentObj.getName();
You cannot access name directly as it is a private member. Use getName()
method on student object to access name.

Declare Static Members in Class:


The static members in an Ext JS class can be accessed without creating an
object using Ext.create() method. It can be accessed using class name with
dot notation same as other programming languages.
Declare static members in Ext JS class using 'statics' parameter as shown
below.
Ext.define('Student', { name : 'unnamed', getName : function()
{ alert('Student name is ' + this.name); }, constructor :
function(studentName){ if(studentName) this.name =
studentName; }, statics : { getSchoolName : function(){
return "XYZ"; } } });//call static
methodalert(Student.getSchoolName());

As you can see in the above example, getSchoolName() function is defined


inside statics parameter object. So now you can call it like
Student.getSchoolName().

Inheritance in Ext JS:


Ext JS supports object-oriented programming concepts such as class,
inheritance, polimorphisham etc. We can inherit a new class from existing
class using extend keyword while defining a new class in Ext JS.
For example, define a Person class with getName method as below.
Ext.define('Person', { name : 'Unknown', constructor : function(name){
if(name){ this.name = name; } }, getName :
function(){ alert("My name is " + this.name); }});

Now, define Student class with extend:'Person' in the config section as


below.
Ext.define('Student', { extend : 'Person', schoolName : 'Unknown',
constructor : function(name, schoolName){ this.schoolName = schoolName
|| 'Unknown'; //call parent class constructor
this.callParent(arguments); }, getSchoolName : function()
{ alert("My school name is " + this.schoolName); }});var newStudent
= new Student('XYZ', 'ABC School');newStudent.getName(); //output:
XYZnewStudent.getSchoolName(); //output: ABC School
As you can see above, Student class inherits Person class using extend
keyword. So now, we can call getName() method on the Student object
which in turn will call the getName() method of Person class.
Try it on https://fiddle.sencha.com/#fiddle/3l1

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');

In the above example, we have included Ext.mixin.Observable mixin using


mixins config so that we can use it. In the constructor, we call
this.mixins.observable.constructor.call(this, config) which initialiazes the
config. In the updateName() method, we fire custom event
studentNameChanged using fireEvent() method with new value. We handle
this event on newStudent instance where we register the handler using on()
method.

Working with DOM:


Ext JS is a DHTML library. It creates the UI by creating or manipulating DOM
elements using JavaScript. As you may know that not all browsers performs
the same operation on DOM elements using the same JavaScript DOM
manipulation methods. There are cross-browser issues associated with DOM
creation and manipulation. To solve cross-browser issues, Ext JS includes
following classes for creating or manipulating the DOM elements.
Class Description
Ext.dom.Element Main class in Ext JS that wraps single HTML DOM
element. It includes DOM manipulating methods
with normalizing cross-browser issues so that
programmers do not have to worry about cross-
browser issues.
Ext.dom.CompositeElement It encapsulates a collection of HTML DOM
elements. Includes methods to manipulate, filter, or
perform specific action on the collection of DOM
elements.
Ext.dom.Helper It includes methods to create DOM elements using
specified attributes like tag, children, cls, and html.
Ext.dom.Query Allows us to search for the dom elements using
CSS3 Selectors, it's own selectors and basic XPath
query syntax.

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.

The following example demonstrates how to take a reference of DOM


elements.
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title> <script src="../../ext-4.2.1/ext-4.2.1.883/ext-
debug.js"></script> <script> Ext.onReady(function () {
// get Ext.dom.Element object var txtFirst =
Ext.get("txtFirstName"); txtFirst.set({ 'value': 'Steve' });
Ext.fly('txtLastName').set({ 'value': 'Jobs' });
console.log(txtFirst.$className); }); </script></head><body>
First Name: <input type="text" id="txtFirstName" class="myclass"/> <br /><br
/> Last Name: <input type="text" id="txtLastName" class="myclass" />
</body></html>

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.

Composite Elements in Ext JS:


The composite elements class Ext.dom.CompositeElement wraps multiple
Ext.dom.Element instances. It includes methods which manipulate this group
of Ext.dom.Element instances in a single call so that we don't have to get
the reference of each Ext.dom.Element and perform the same operation for
each elements separately.
The composite elements can be retrieved using Ext.select() method. The
Ext.select() method takes CSS selector as a string parameter and returns an
instance of Ext.dom.CompositeElement or Ext.dom.CompositeElementLite.
Ext.select(selector, [unique], [root] )

The following example demonstrates how to manipulate multiple DOM


elements in a single method call.
<!DOCTYPE html><html xmlns="https://www.w3.org/1999/xhtml"><head>
<title></title> <script src="../../ext-4.2.1/ext-4.2.1.883/ext-
debug.js"></script> <script> Ext.onReady(function () {
// get all input elements and set their bgcolor to yellow var
inputElements = Ext.select("input");
inputElements.set({ 'style': 'background-color:yellow' }); });
</script></head><body> First Name: <input type="text" id="txtFirstName"
class="myclass"/> <br /><br /> Last Name: <input type="text"
id="txtLastName" class="myclass" /> </body></html>

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

The following example demonstrates how to create DOM elements using


Ext.DomHelper class.
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title> <script src="../../ext-4.2.1/ext-4.2.1.883/ext-
debug.js"></script> <script> Ext.onReady(function () {
var dh = Ext.DomHelper; // ExtJS DomHelper Utility Class var
listItems = { id: 'dhlist', tag: 'ul',
children: [{ tag: 'li', html: 'item 1'
}, { tag: 'li', html: 'item 2'
}, { tag: 'li', html: 'item 3'
}] } dh.append("div1", listItems); });
</script></head><body> <div id="div1"> </div></body></html>

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').

Component Life Cycle:


Each component in Ext JS passes through following three stages:
Stage Description
Initialization Registering the component with
Ext.ComponentManager and deciding if a
component will be rendered.
Rendering Creating the DOM for the component and adding it
to the DOM hierarchy with the events, CSS, etc..
Destruction Removing the events, the DOM object and
unregistering the component from the
Ext.ComponentManager

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.

Adding Components to Container:


You can add different types of Ext JS components into a container using
items config property or add() method.
Note: Container can also include another container.
The following example demonstrates how to add components into a
container using items config as well as add() method.
Ext.onReady(function () { var comp1 = Ext.create('Ext.Component', {
html:'Component 1' }); var comp2 =
Ext.create('Ext.Component', { html: 'Component 2' }); var comp3
= Ext.create('Ext.Component', { html: 'Component 3' }); var
comp4 = Ext.create('Ext.Component', { html: 'Component 4' });
var container1 = Ext.create('Ext.container.Container', { style:
{ borderColor: 'Red', borderStyle: 'solid', borderWidth: '1px' },
width: '50%', padding: '5 5 5 5', items: [comp3, comp4] });
// adding compoents into container using items config var container2 =
Ext.create('Ext.container.Container', { renderTo: Ext.getBody(),
title: 'Container', border: 1, width: '50%', padding:'5
5 5 5', style: { borderColor: '#000000', borderStyle: 'solid',
borderWidth: '1px' }, items: [comp1, comp2] }); // adding
container into container container2.add(container1);});

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.

Ext JS provides different types of layouts to arrange child components into a


container. Learn about the layouts in the next section.

Layouts in Ext JS:


When you add UI component within a container, you need to define their
layout properties. Layout tells a container how to arrange a child component.
In order to use a layout, your component must be of type
Ext.container.Container or something which inherits from it. All layouts
inherit from Ext.layout.container.Container.
You can set the layout either as a string or an object:
layout: 'auto'//orlayout: { type: 'auto'}

Following are different Layouts available in Ext JS:


Layout Description
Absolute This layout inherits anchor layout and adds the
ability of positioning the component at particular
co-ordinates using standard x, y config options.
Accordion This layout manages multiple panels in an
expandable accordion style. By default one panel
can be expanded at any given time, but you can also
expand multiple panels using multi config.
Anchor This layout enables anchoring of contained
elements relative to the container's dimensions.
Please visit Anchor Rules.
Auto This layout is applicable when no layout is
configured into a container. AutoLayout provides
only a passthrough of any layout calls to any child
containers.
Border This is a multi-pane, application-oriented UI layout
style that supports multiple nested panels,
automatic bars between regions and built-in
expanding and collapsing of regions.
Card This layout manages multiple child Components,
each fitted to the Container, where only a single
child Component can be visible at any given time.
This layout style is most commonly used for wizards
and tab implementations.
Fit This layout is used in a container that contains a
single item that automatically expands to fill the
container.
Form This is a layout that will render form Fields, one
under the other all stretched to the Container
width.
HBox A layout that arranges items horizontally across a
Container. align, flex and pack are important config
options for this layout.
Table This layout allows you to easily render content into
an HTML table.
VBox A layout that arranges items vertically down a
Container. align, flex and pack are important config
options for this layout.

The following example demonstrates layouting child components horizontally


and vertically into a container.
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title> <script src="../../ext-4.2.1/ext-4.2.1.883/ext-
debug.js"></script> <link href="../../ext-4.2.1/ext-
4.2.1.883/resources/css/ext-all.css" rel="stylesheet" /></head><body>
<script> Ext.onReady(function () { var comp1 =
Ext.create('Ext.Component', { html: 'Component 1',
padding:'5 5 5 5' }); var comp2 =
Ext.create('Ext.Component', { html: 'Component 2',
padding: '5 5 5 5' }); var comp3 =
Ext.create('Ext.Component', { html: 'Component 3',
padding: '5 5 5 5' }); var comp4 =
Ext.create('Ext.Component', { html: 'Component 4',
padding: '5 5 5 5' }); var container =
Ext.create('Ext.container.Container', { layout: { type: 'vbox'
}, items: [comp3, comp4] });
Ext.create('Ext.container.Container', { style: { borderColor:
'Red', borderStyle: 'solid', borderWidth: '1px' }, renderTo:
Ext.getBody(), padding: '5 5 5 5', layout:
{ type: 'hbox' }, items: [comp1, comp2,
container] }); }); </script> </body></html>

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.

The following example demonstrates how to search components using


Ext.ComponentQuery.query() method.
Ext.onReady(function () { Ext.create('Ext.container.Container',
{ id:'myContainer', renderTo: Ext.getBody(), padding: '5
5 5 5', layout: { type: 'vbox' }, items: [ {
xtype: 'textfield', fieldLabel:'First Name' },
{ xtype: 'textfield', fieldLabel: 'Last Name'
}, { xtype: 'panel', layout:'vbox',
items: [ { xtype: 'datefield',
fieldLabel: 'Date of Birth' }, {
xtype: 'container', items: [
{ xtype: 'textfield',
fieldLabel: 'email', itemId:'email'
} ] } ] }
] }); var dateFields = Ext.ComponentQuery.query('container
datefield'); console.log('DateField in Containers: ');
console.log(dateFields); var dateFieldsInPanels =
Ext.ComponentQuery.query('panel > datefield'); console.log('Child
DateField in Panel: ' ); console.log(dateFieldsInPanels); var
emailInMyContainer = Ext.ComponentQuery.query('#myContainer > #email');
console.log('#email inside #myContainer');
console.log(emailInMyContainer);});

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); }});

In the above viewport class, it includes different regions in viewport to


separate different sections of the application view such as header, left bar,
right bar, center area and footer area. Ext.container.Panel is the default xtype
in Viewport item collection.
Now, to handle events from the above viewport class, add ViewportController
class. For that, create app -> view -> ViewportController.js and define
School.view.ViewportController class as shown below.

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

Custom Message Box:


You can customize a message box based on your requirement by passing
different configuration options.
Ext.Msg.show({ title : 'Save', msg : 'Do you
want to Save the changes? ', width : 300,
closable : false, buttons : Ext.Msg.YESNOCANCEL,
buttonText : { yes : 'Yes & Continue',
no : 'No & Continue', cancel : 'Discard' },
multiline : false, fn : function(buttonValue, inputText,
showConfig){ Ext.Msg.alert('Status', buttonValue);
}, icon : Ext.Msg.QUESTION });

Try it on https://fiddle.sencha.com/#fiddle/3kt

ProgressBar in Ext JS:


You can display progress bar in ExtJS 4 using Ext.ProgressBar class. It
supports two different modes: Manual and Automatic.
In the manual mode, you are responsible for showing, updating (via
updateProgress) and clearing the progress bar as needed from your own
code. This method is most appropriate when you want to show progress
throughout the operation that has predictable points of interest at which you
can update the control.
Following is an example of manual progress bar using updateProgress
method:

for(var i = 0; i < 11; i ++ ){ progBar.updateProgress((i * 0.1),


'updating', 'saving..'); //write code which takes times to execute in
each iteration }progBar.updateText('Saved Successfully!');

Automatic progress bar using wait method:


progBar.wait({ duration : 10000, increment : 12, text : 'Saving...',
scope : this, fn : function(){ progBar.updateText('Saved
Successfully!'); }});

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.

You might also like