About this book

Ext JS 4 is a JavaScript framework that provides resources to build Rich Internet Applications with great performance. Ext JS 4 has been packed with many new features and it is difficult to master, even for seasoned experts in Ext JS 3.

Ext JS 4 First Look teaches you the main functional areas of Ext JS 4 that have significant new features, explains the new features and how to use them, while highlighting the differences between Ext JS 4 and the previous versions.

This book will give you the knowledge to make the required changes to Ext JS 3 application to build a complete Ext JS 4 application.

This book provides examples of how to load Ext JS components by demand, charts, grid, tree, forms and panels, new data model, themes and mvc architecture.

Ext JS 4 First Look provides full examples and illustrations to help you easily learn the new features of Ext JS 4.

Publication date:
January 2012
Publisher
Packt
Pages
340
ISBN
9781849516662

 

Chapter 1. What's New in Ext JS 4?

Ext JS 4 is the biggest overhaul that has been made to the Ext framework. These changes include a new class system, introduction of a new platform, many API changes and enhancements, and new components, such as the new charts and new draw components. Ext JS 4 is faster, more stable, and easy to use.

In this chapter, you will learn the following:

  • How to get started with Ext JS 4

  • How the Ext JS platform is now organized

  • The new Ext JS 4 class system

  • Ext JS 4 SDK

  • Ext JS 3 versus Ext JS 4 compatibility

  • Migrating from Ext JS 3 to Ext JS 4

  • A quick overview of new components

Getting started with Ext JS 4

Ext JS is a cross-browser RIA (Rich Internet Application) framework, easy to use with rich UI components, used by one million developers around the world.

The change from Ext JS 1.x to Ext JS 2.x was a major refactoring, including the Component model creation, along with refactoring of many of the existing components. The Ext JS 3.x is backward-compatible with Ext JS 2.x.

Until Ext JS 3, the layout was what expanded most of the time while rendering the application. Ext JS 4 has a vast improvement in this area. The generated HTML was also updated in branch 4.x.

Sencha also created more than 4000 unit tests to provide a more stable framework with 90% code coverage. If a new change is made, they know if anything breaks far before it is released.

Some API improvements include standardized API with name conventions and a simpler configuration (you write fewer lines of code to achieve the same results as with previous versions).

Package and namespace updates

Some API improvements include standardized API with a name convention.

For example, in Ext JS 3, classes such as PagingToolbar, Toolbar, and Spacer are grouped under the package widgets (along with other classes). These classes are also defined directly on the Ext global object, which means you can access them through Ext.PagingToolbar, Ext.Toolbar, and so on.

In Ext JS 4, every class has been placed into packages and namespaces, based on its functionality. For example, PagingToolbar, Toolbar, Spacer and other toolbar-related classes are now grouped into the new toolbar package and are grouped into a new Ext.toolbar namespace. Some of the classes were also renamed based on the new namespaces.

Other packages, such as button, view, picker, slider, tab, window, tip, tab, and menu (along with many others), follow this new package name and namespace update as well. A full list of these changes is provided in Appendix A,Ext JS 4 Versus Ext JS 3 Class Names.

All the classes that were reorganized are still available via the new alternateClassName property, so Ext JS 3 class names will still work under Ext JS 4. For example, the alternative class name of Ext.toolbar.PagingToolbar is Ext.PagingToolbar. You can read the list of all Ext JS 4 alternative class names in Appendix A,Ext JS 4 Versus Ext JS 3 Class Names.

Note

Although we are using the new alternate class name property, it is recommended that you migrate to the new convention names in your code. For example, in Ext JS 3, we have the Ext.PagingToolbar component. In Ext JS 4, we can create a new instance declaring Ext.create(Ext.PagingToolbar), using PagingToolbar (Ext JS 3 name). But, it is highly recommended not to use the alternative class name (Ext JS 3 name), since we have a new name for this class in Ext JS 4 (Ext.create(Ext.toolbar.PagingToolbar)).

Upgraded documentation

The Ext JS 4 documentation is one of its most-used resources, because it is easy to use. The Ext documentation has always been good, with a clean and easy to use UI (User Interface). We will learn how to access the documentation offline, but we can also access it online at http://docs.sencha.com/ext-js/4-0.

The documentation from previous versions was a little vague, with some examples that sometimes were not very useful. When you first open the documentation, you will see a welcome page. At the top-left corner, we will see the following tabs: Home, API Documentation, Guides, Videos, and Examples.

When we click on the API Documentation tab, we will see the list of all packages on the left side and the center portion. There will be a list of the most relevant classes organized in the following topics: Base, View, Components, Data, and Utilities.

We can visualize the list of Ext JS classes by package or by inheritance.

When you click on a class, its documentation will get opened in the center portion of the screen. All the content is loaded via AJAX, as we can see in the following screenshot:

On the top of the page, you will see an icon indicating whether the class you have opened is a singleton class or a component, followed by the class name. If it is a component, the xType (when available) will be displayed as well.

Below the class name, you will see a menu with the following options: Configs, Properties, Methods, Events, Super Classes, and Sub Classes (depending on the class, some of these items will be not available), followed by a search field, where you can easily find a particular property, config, method, and so on.

Then there is a description of what the class does, and, when available, an example showing how to use it. Some of the portions of code available in the documentation have a preview option, so we can see what the code would output if we executed it.

On the right side of the Document tab we have opened, we can see the ALTERNATE NAMES of the current class, the HIERARCHY, and the list of the MIXINS of this class. Ext JS 4 documentation also has added support for deprecated members.

There is also a Print button we can click on, by which a print version of the class documentation will be presented.

On the top-right corner of the Ext JS 4 API documentation, we can see a Search box, where we can search for any Ext JS class name, method, configuration option, property, event, and mixins. This update is very useful for daily work. Ext JS 3 allowed searching for class names only.

The new documentation also includes official Ext JS 4 guides to some of the most relevant features of the framework.

As you can see, the Ext JS 4 documentation is improved and is more user-friendly. But is the usage of the API easier to use? Let's take a look at it.

Ext JS 4 SDK quick look

When we download the Ext JS 4 SDK from the Sencha website, we get a zip file. After downloading it, uncompress it to a folder, preferably named extjs.

This is how the Ext JS 4 SDK should look:

First, let's take a look at the JavaScript files located in the root folder (extjs):

  • ext-all.js: This file contains the entire Ext JS framework, everything we need

  • ext.js: This file contains the minimum Ext JS code (Ext JS base library)

Note

If we take a closer look at the previous screenshot, we will see there are more than three versions of the ext-all.js file and two versions of the ext.js file. How and when do we use these files? What is the difference between them?

ext-all.js or ext.js: These are minified files; recommended for use in production environments.

*-dev.js: This file is not minified and contains the debug code; recommended for use in development or testing environments.

*-debug.js or * debug-w-comments: These are not minified and do not contain the debug code; recommended for use in testing environments. The file *-debug-w-comments is bigger than the *-debug.js file and we should avoid using it if the editor is having memory issues.

The SDK also includes the documentation, examples, and the complete source code:

  • docs: This contains the complete documentation (you need to deploy it on a local server to be able to run it). You can also access it online at http://docs.sencha.com/ext-js/4-0/.

  • examples: This contains examples of how to use Ext JS components.

  • overview: This contains a quick overview file with the list of new features, a commented release note.

  • pkgs: This contains the Ext JS modules, packaged up.

  • resources: This contains the CSS and image files used by the Ext themes.

  • src: This is the complete Ext JS source code.

  • welcome: This contains image files used by the index.html file, located in the root folder.

  • builds: This contains additional Ext JS files.

  • jsbuilder: This contains the files for JSBuilder, a project building tool.

Note

For more information about JSBuilder, please go to http://www.sencha.com/products/jsbuilder.

Inside the builds folder, we will find the following files:

  • ext-all-sandbox.js: Ext JS 4 is sandboxed and this is the file that replaces ext-all.js and ext-base.js in sandbox mode

  • ext-core.js: This is Ext JS core library

  • ext-foundation.js: This is the foundation library for Ext JS 4

  • These files also have the debug and dev versions.

Note

Note that the adapter folder is no longer in the Ext JS 4 SDK.

What is the difference between ext.js and ext-all.js?

When we start the development of a new Ext JS project, the first thing we have to do is to add the imports of Ext JS files on the HTML page. If we choose a version of the ext-all file, the browser will load the entire Ext JS framework. If we choose a version of the ext.js file, the browser will load the minimum code required to execute the application, and we can make use of the new dynamic loading feature.

For development and testing, we can use ext.js, because it will use only the required Ext JS code to run the application; but, we cannot forget to add the src folder to the application extjs directory. For production, we can use the ext-all.js file, because it already contains the entire Ext JS framework and has good performance.

Note

There is also a file named bootstrap.js; instead of importing ext-all.js into your HTML page, you can import bootstrap.js. The only thing that this file does is import ext-all.js or ext-all-debug.js, depending on the environment you are using. It will load ext-all-debug.js in the following cases:

1. Current hostname is localhost.

2. Current hostname is an IP(v4) address.

3. Current protocol is a file.

4. Otherwise, bootstrap will load the ext-all.js file.

Deploying Ext JS locally

Some examples and the documentation use Ajax calls to load their content. If we try to load these examples locally, they will not work. To see them in our local computer, we have to deploy extjs on a local server. To do so, we simply need to place the extjs folder inside the web root folder of the local web server. Depending on the operating system you are using your web root directory will be located at:

  • Windows: C:\Program Files\Apache Software Foundation\Apache2.2\htdocs

  • Linux: /var/www/

  • Mac OS X: /Library/WebServer/Documents/

After doing that, we can access Ext JS locally at the URL http://localhost/extjs/index.html.

Note

In the next topic, we will start showing some code snippets of the new Ext JS 4 features. As we deployed Ext JS 4 locally, we will also create the example code in a web server. To do so, we will create a folder named ext4firstlook to host the code presented in this book. And, as we are on Chapter 1, we will place the code in ext4firstlook/chapter01.

 

Getting started with Ext JS 4


Ext JS is a cross-browser RIA (Rich Internet Application) framework, easy to use with rich UI components, used by one million developers around the world.

The change from Ext JS 1.x to Ext JS 2.x was a major refactoring, including the Component model creation, along with refactoring of many of the existing components. The Ext JS 3.x is backward-compatible with Ext JS 2.x.

Until Ext JS 3, the layout was what expanded most of the time while rendering the application. Ext JS 4 has a vast improvement in this area. The generated HTML was also updated in branch 4.x.

Sencha also created more than 4000 unit tests to provide a more stable framework with 90% code coverage. If a new change is made, they know if anything breaks far before it is released.

Some API improvements include standardized API with name conventions and a simpler configuration (you write fewer lines of code to achieve the same results as with previous versions).

Package and namespace updates

Some API improvements include standardized API with a name convention.

For example, in Ext JS 3, classes such as PagingToolbar, Toolbar, and Spacer are grouped under the package widgets (along with other classes). These classes are also defined directly on the Ext global object, which means you can access them through Ext.PagingToolbar, Ext.Toolbar, and so on.

In Ext JS 4, every class has been placed into packages and namespaces, based on its functionality. For example, PagingToolbar, Toolbar, Spacer and other toolbar-related classes are now grouped into the new toolbar package and are grouped into a new Ext.toolbar namespace. Some of the classes were also renamed based on the new namespaces.

Other packages, such as button, view, picker, slider, tab, window, tip, tab, and menu (along with many others), follow this new package name and namespace update as well. A full list of these changes is provided in Appendix A,Ext JS 4 Versus Ext JS 3 Class Names.

All the classes that were reorganized are still available via the new alternateClassName property, so Ext JS 3 class names will still work under Ext JS 4. For example, the alternative class name of Ext.toolbar.PagingToolbar is Ext.PagingToolbar. You can read the list of all Ext JS 4 alternative class names in Appendix A,Ext JS 4 Versus Ext JS 3 Class Names.

Note

Although we are using the new alternate class name property, it is recommended that you migrate to the new convention names in your code. For example, in Ext JS 3, we have the Ext.PagingToolbar component. In Ext JS 4, we can create a new instance declaring Ext.create(Ext.PagingToolbar), using PagingToolbar (Ext JS 3 name). But, it is highly recommended not to use the alternative class name (Ext JS 3 name), since we have a new name for this class in Ext JS 4 (Ext.create(Ext.toolbar.PagingToolbar)).

Upgraded documentation

The Ext JS 4 documentation is one of its most-used resources, because it is easy to use. The Ext documentation has always been good, with a clean and easy to use UI (User Interface). We will learn how to access the documentation offline, but we can also access it online at http://docs.sencha.com/ext-js/4-0.

The documentation from previous versions was a little vague, with some examples that sometimes were not very useful. When you first open the documentation, you will see a welcome page. At the top-left corner, we will see the following tabs: Home, API Documentation, Guides, Videos, and Examples.

When we click on the API Documentation tab, we will see the list of all packages on the left side and the center portion. There will be a list of the most relevant classes organized in the following topics: Base, View, Components, Data, and Utilities.

We can visualize the list of Ext JS classes by package or by inheritance.

When you click on a class, its documentation will get opened in the center portion of the screen. All the content is loaded via AJAX, as we can see in the following screenshot:

On the top of the page, you will see an icon indicating whether the class you have opened is a singleton class or a component, followed by the class name. If it is a component, the xType (when available) will be displayed as well.

Below the class name, you will see a menu with the following options: Configs, Properties, Methods, Events, Super Classes, and Sub Classes (depending on the class, some of these items will be not available), followed by a search field, where you can easily find a particular property, config, method, and so on.

Then there is a description of what the class does, and, when available, an example showing how to use it. Some of the portions of code available in the documentation have a preview option, so we can see what the code would output if we executed it.

On the right side of the Document tab we have opened, we can see the ALTERNATE NAMES of the current class, the HIERARCHY, and the list of the MIXINS of this class. Ext JS 4 documentation also has added support for deprecated members.

There is also a Print button we can click on, by which a print version of the class documentation will be presented.

On the top-right corner of the Ext JS 4 API documentation, we can see a Search box, where we can search for any Ext JS class name, method, configuration option, property, event, and mixins. This update is very useful for daily work. Ext JS 3 allowed searching for class names only.

The new documentation also includes official Ext JS 4 guides to some of the most relevant features of the framework.

As you can see, the Ext JS 4 documentation is improved and is more user-friendly. But is the usage of the API easier to use? Let's take a look at it.

Ext JS 4 SDK quick look

When we download the Ext JS 4 SDK from the Sencha website, we get a zip file. After downloading it, uncompress it to a folder, preferably named extjs.

This is how the Ext JS 4 SDK should look:

First, let's take a look at the JavaScript files located in the root folder (extjs):

  • ext-all.js: This file contains the entire Ext JS framework, everything we need

  • ext.js: This file contains the minimum Ext JS code (Ext JS base library)

Note

If we take a closer look at the previous screenshot, we will see there are more than three versions of the ext-all.js file and two versions of the ext.js file. How and when do we use these files? What is the difference between them?

ext-all.js or ext.js: These are minified files; recommended for use in production environments.

*-dev.js: This file is not minified and contains the debug code; recommended for use in development or testing environments.

*-debug.js or * debug-w-comments: These are not minified and do not contain the debug code; recommended for use in testing environments. The file *-debug-w-comments is bigger than the *-debug.js file and we should avoid using it if the editor is having memory issues.

The SDK also includes the documentation, examples, and the complete source code:

  • docs: This contains the complete documentation (you need to deploy it on a local server to be able to run it). You can also access it online at http://docs.sencha.com/ext-js/4-0/.

  • examples: This contains examples of how to use Ext JS components.

  • overview: This contains a quick overview file with the list of new features, a commented release note.

  • pkgs: This contains the Ext JS modules, packaged up.

  • resources: This contains the CSS and image files used by the Ext themes.

  • src: This is the complete Ext JS source code.

  • welcome: This contains image files used by the index.html file, located in the root folder.

  • builds: This contains additional Ext JS files.

  • jsbuilder: This contains the files for JSBuilder, a project building tool.

Note

For more information about JSBuilder, please go to http://www.sencha.com/products/jsbuilder.

Inside the builds folder, we will find the following files:

  • ext-all-sandbox.js: Ext JS 4 is sandboxed and this is the file that replaces ext-all.js and ext-base.js in sandbox mode

  • ext-core.js: This is Ext JS core library

  • ext-foundation.js: This is the foundation library for Ext JS 4

  • These files also have the debug and dev versions.

Note

Note that the adapter folder is no longer in the Ext JS 4 SDK.

What is the difference between ext.js and ext-all.js?

When we start the development of a new Ext JS project, the first thing we have to do is to add the imports of Ext JS files on the HTML page. If we choose a version of the ext-all file, the browser will load the entire Ext JS framework. If we choose a version of the ext.js file, the browser will load the minimum code required to execute the application, and we can make use of the new dynamic loading feature.

For development and testing, we can use ext.js, because it will use only the required Ext JS code to run the application; but, we cannot forget to add the src folder to the application extjs directory. For production, we can use the ext-all.js file, because it already contains the entire Ext JS framework and has good performance.

Note

There is also a file named bootstrap.js; instead of importing ext-all.js into your HTML page, you can import bootstrap.js. The only thing that this file does is import ext-all.js or ext-all-debug.js, depending on the environment you are using. It will load ext-all-debug.js in the following cases:

1. Current hostname is localhost.

2. Current hostname is an IP(v4) address.

3. Current protocol is a file.

4. Otherwise, bootstrap will load the ext-all.js file.

Deploying Ext JS locally

Some examples and the documentation use Ajax calls to load their content. If we try to load these examples locally, they will not work. To see them in our local computer, we have to deploy extjs on a local server. To do so, we simply need to place the extjs folder inside the web root folder of the local web server. Depending on the operating system you are using your web root directory will be located at:

  • Windows: C:\Program Files\Apache Software Foundation\Apache2.2\htdocs

  • Linux: /var/www/

  • Mac OS X: /Library/WebServer/Documents/

After doing that, we can access Ext JS locally at the URL http://localhost/extjs/index.html.

Note

In the next topic, we will start showing some code snippets of the new Ext JS 4 features. As we deployed Ext JS 4 locally, we will also create the example code in a web server. To do so, we will create a folder named ext4firstlook to host the code presented in this book. And, as we are on Chapter 1, we will place the code in ext4firstlook/chapter01.

 

The new Ext JS 4 class system


Ext JS has always provided a class system of its own; this enables developers to write code with a more object-oriented approach, since JavaScript has no classes of its own. Ext JS 4 introduces a new class system to make development easier and more flexible and also introduces some new features. These changes are backward-compatible with the Ext JS 3 class system. The new features are as follows:

  • Class definition and creation

  • Mixins

  • Automatic getters and setters

  • Dynamic class loading

  • Statics

Class definition and creation

Ext JS 4 introduces the Ext.define and Ext.create functions to define and create new classes.

In this topic, we will see how to create a new Ext JS class from scratch and how to instantiate it using the new capabilities of Ext JS 4.

Creating a new class

To define a new class using Ext JS 3, we have to extend the Object class as follows:

MyApp.NewClass = Ext.extend(Object, {
//class functionalities here
});

Note

Downloading the example code

You can download the example code files for all Packt books you have purchased using your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

In Ext JS 4, we define a new class as follows:

Ext.define('MyApp.NewClass', {
//class functionalities here
});

The Ext.extend is deprecated; it is recommended to use Ext.define instead.

Extending a class

Let's compare the code between Ext JS 3 and Ext JS 4 to create the following customized window (extending Ext.Window):

This is how we do it in Ext JS 3:

Ext.namespace('MyApp');
MyApp.MyWindow = Ext.extend(Ext.Window, {
title: 'Welcome!',
initComponent: function() {
Ext.apply(this, {
items: [
{
xtype: 'textfield',
name: 'tfName',
fieldLabel: 'Enter your name'
}
]
});
MyApp.MyWindow.superclass.initComponent.apply(this, arguments);
}
});
var win = new MyApp.MyWindow();
win.show();

There is nothing wrong with the code above, right? Correct. But, if you forget to declare the namespace, you will get the error MyApp is not defined; if, when you are loading your application, Ext.Window is not defined as well, you will also get an error and your application will crash.

In Ext JS 4, these problems are resolved with the use of Ext.define:

Ext.define('MyApp.MyWindow', {
extend: 'Ext.Window',
title: 'Welcome!',
initComponent: function() {
this.items = [{
xtype: 'textfield',
name: 'tfName',
fieldLabel: 'Enter your name'
}],
this.callParent(arguments);
}
});
var win = Ext.create('MyApp.MyWindow');
win.show();

We can refer to Ext classes using string, which means we will not get the errors mentioned previously. Ext JS 4 class manager will check if Ext.Window has been defined already, and if not, will defer the creation of MyApp.MyWindow until it is defined. This way, we do not have to maintain a load order in our applications; the Ext framework will manage everything.

Another difference we can see in the code is the simplified call to the superclass to apply the subclass arguments. Instead of calling MyApp.MyWindow.superclass.initComponent.apply(this, arguments), we simply call this.callParent(arguments).

And instead of instantiating the MyApp.MyWindow class using the keyword new, we use the Ext.create function.

We can still use the new keyword to instantiate Ext JS classes instead of Ext.create, but then we will not have all the benefits of Ext JS 4 class system features; we will talk about these features in the next topic.

The Ext.define is an alias of Ext.ClassManager.create, and Ext.create is an alias of Ext.ClassManager.instantiate.

Another benefit of using Ext.define is that it will automatically detect and create new namespaces, as needed.

Note

Note that we do not have to specify the MyApp namespace in Ext JS 4. The framework will detect that it has not been created and will create it.

Mixins

The mixins configuration is a brand new concept for Ext JS. Mixins define reusable sets of behavior and configuration that can be 'mixed in' to a class. In other words, it allows merging new capabilities (functions or properties) to the class prototype.

Note

For more information about the mixins concept, please read http://en.wikipedia.org/wiki/Mixin.

It is very similar to the Ext.override function, but it does not replace (override) the existing methods.

The mixin can be as simple as follows:

Ext.define('MyApp.mixins.Log', {
startLogging: function() {
console.log('called funcion startLogging');
}
});

And this is how we configure the mixin in a class:

Ext.define('MyApp.MyWindow', {
extend: 'Ext.Window',
mixins: {
console: 'MyApp.mixins.Log'
},
...
});

Note that we referenced all class names by string, thus we do not get any errors if the mixins are not loaded on the page yet.

When we instantiate the MyApp.MyWindow, we can call the startLogging function:

var win = Ext.create('MyApp.MyWindow');
win.startLogging();

And the following screenshot shows the output (simply writes called funcion startLogging on the console):

You can have as many mixins in a class as you want; it is a great way to get multiple inheritance.

Config (auto setters and getters)

Ext JS 4 introduces the config declaration. There are some classes in Ext JS; you can pass some configuration parameters and you can change these parameters at runtime using getter and setter methods. When you configure properties in the config declaration, Ext JS 4 will automatically generate four methods: getter, setter, reset, and apply.

Let's apply the config declaration on the MyApp.MyWindow class:

Ext.define('MyApp.MyWindow', {
extend: 'Ext.Window',
config: {
title: 'Welcome!'
}
});

In the preceding code, the default value for title is Welcome!.

Note that now that we have configured the title property inside the config, the framework will create the following methods automatically for you:

  • getTitle: This returns the current title.

  • setTitle: This will set a new value for title.

  • resetTitle: This will set the title to its default value.

  • applyTitle: This method is called every time setTitle is called. You can implement a custom code for it.

After we instantiate the MyApp.MyWindow class, we can call any of these methods:

var win = Ext.create('MyApp.MyWindow');
win.setTitle('I changed the title');
win.show();

The following screenshot shows our output:

In Ext JS 3.3, we had to manually create it:

Ext.namespace('MyApp');
MyApp.MyWindow = Ext.extend(Ext.Window, {
title: 'Welcome!',
getTitle: function() {
return this.title;
},
resetTitle: function() {
this.setTitle('Welcome!');
},
setTitle: function(newTitle) {
this.title = this.applyTitle(newTitle) || newTitle;
},
applyTitle: function(newTitle) {
this.title = newTitle;
}
});

If you need to override any of these methods for any reason, it is very simple. You just need to add the code to your class declaration:

Ext.define('MyApp.MyWindow', {
extend: 'Ext.Window',
config: {
title: 'Welcome!'
},
applyTitle: function(newTitle) {
this.title = 'Updated to: '+newTitle;
}
});

This automatic generation of code will save a lot of development time, save some lines of code (and this means your code will be smaller), and add a name convention, resulting in a more consistent API.

Dynamic class loading

The dynamic class loading system is another new feature for Ext JS 4. It also provides an integrated dependency management system.

This new feature is optional and you should avoid using it in production, though it is very useful for the development environment. We are going to learn why it is so useful:

In previous versions of Ext JS, if you wanted to use the following code, you had to wait until the entire framework was loaded, correct? If you tried to use it before the framework was loaded, you would probably get an error:

var win = new Ext.Window({
title : 'Hello!',
width : 100,
height: 50
});
win.show();

This behavior changes in Ext JS 4. We can ask Ext JS to load the classes that we need to use and then call a function when it is finished loading. For example:

Ext.require('Ext.Window', function() {
var win = new Ext.Window({
title : 'Hello!',
width : 100,
height: 50
});
win.show();
});

When we use Ext.require, we are telling Ext JS we need Ext.Window before calling the function. The framework will also resolve any dependencies that the loaded class has.

To use this feature, you have to use Ext.define and define the dependencies in the code using two new class properties:

  • Requires: This declares the class dependencies required for a class to work. These classes are going to be loaded before the current class gets instantiated.

  • Uses: This declares the optional class dependencies, but is not required. These classes do not have to be available before the current class gets instantiated.

The Loader is recursive. If any class has dependencies that are not yet loaded, it will keep loading all the required classes until all of them are ready. All these dependencies are managed internally. This means you do not need to manage all those script tags in the HTML page, because the class loader will do it for you. This kind of flexibility is very useful in the development environment, when this is more important than page speed.

You have to be careful with deadlocks. When you declare your own classes, make sure there is no deadlock; otherwise, your application may crash. For example, let's say we have the following classes: A, B, and C. Class A extends class B, class B extends class C, and class C extends class A, as shown in the following code:

Ext.define('deadlock.A', {
extend: 'deadlock.B'
});
Ext.define('deadlock.B', {
extend: 'deadlock.C'
});
Ext.define('deadlock.C', {
extend: 'deadlock.A'
});

Now, we are going to try to execute a function that requires class A:

Ext.Loader.setConfig({
enabled: true,
paths: {'deadlock':'deadlock'}
});
Ext.onReady(function(){
Ext.require(['deadlock.A'], function() {
alert("Loaded: " + Ext.Loader.history.join(" => "));
});
});

In the HTML file, we are not going to import the files A, B, and C. That is because we are using the Ext.Loader. In this configuration, we can point to a directory where the files we need are located All the three files belong to the deadlock package, so they are located in the deadlock folder, as shown in the following screenshot:

This way, we can configure as many package names as we need. Note that we are only importing the basic Ext JS files in the HTML:

<html>
<title>Ext JS 4</title>
</head>
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="../extjs/ext-all-debug.js"></script>
<script type="text/javascript">
//our code here
</script>
<body>
</body>
</html>

And if you try to execute the preceding code, you will get the following error:

Uncaught Error: [Ext.Loader] Deadlock detected! 'deadlock.C' and 'deadlock.A' mutually require each others. Path: deadlock.C -> deadlock.A -> deadlock.B -> deadlock.C
Uncaught Error: [Ext.Loader] The following classes are not declared even if their files have been loaded: deadlock.A, deadlock.B, deadlock.C. Please check the source code of their corresponding files for possible typos:
deadlock/A.js,
deadlock/B.js,
deadlock/C.js

Because of the dependencies, the Ext management system will try to load C for the first class. But C needs class A, and so on. This will lead us to a loop, causing a deadlock.

Now let's take a look at another example. We have three classes: A (which extends B and has a mixin named Mixin), B (which extends C), and C (which uses A). Remember the keyword uses does a reference to the classes that are not required to be loaded before the class is instantiated. In this case, we will not have a deadlock:

Ext.define('noDeadlock.A', {
extend: 'noDeadlock.B',
mixins: {
console: 'noDeadlock.Mixin'
}
});
Ext.define('noDeadlock.B', {
extend: 'noDeadlock.C'
});
Ext.define('noDeadlock.C', {
uses: 'noDeadlock.A'
});
Ext.define('noDeadlock.Mixin', {
log: function() {
console.log('called function log');
}
});

In the HTML page, we are going to import only the necessary files to load our code. We are not going to include the classes A, B, C, and Mixin.

<html>
<head>
<title>Ext JS 4</title>
</head>
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="../extjs/ext-all-debug.js"></script>
<script type="text/javascript">
//our code here
</script>
<body>
</body>
</html>

To import the classes which are in the js/myApp folder, we are going to use the Ext.Loader class, which will take care of everything for us:

Ext.Loader.setConfig({
enabled: true,
paths: {'noDeadlock':'noDeadlock'}
});
Ext.onReady(function(){
Ext.require(['noDeadlock.A'], function() {
alert("Loaded: " + Ext.Loader.history.join(" => "));
});
});

And when we execute this code, we have the following output:

Loaded: noDeadlock.Mixin => noDeadlock.C => noDeadlock.B => noDeadlock.A

This new class system is 100% backward-compatible.

Statics

In Ext JS 4, any class can define static methods, which means you do not need to instantiate the class to call the method; you can call ClassName.methodName().

To declare a static method or property, simply define it as statics in its class property.

Let's take a look at the following example:

Ext.define('MyApp.Math', {
statics: {
count: 0,
appName: 'Math',
sum: function(number1, number2) {
return number1 + number2;
}
},
constructor: function() {
this.statics().count++;
console.log('You instantiated the class: ' + this.self.appName);
console.log('App Name: ' + this.statics().appName);
console.log('Count is: ' + this.statics().count);
}
});

The class MyApp.Math contains two static properties—count and appName. This means we can access the value of these properties without instantiating the class as follows:

MyApp.Math.count;
MyApp.Math.appName;

We can also access the method sum:

MyApp.Math.sum(1,2); //output is 3

Now let's take a closer look at the constructor code to see how we can access these properties outside the statics declaration. When you use this.statics() you have access to any static property or method inside the class. When you use this.self.propertyName, it depends on which instance you are referring to. It is important if you work with inheritance.

For example, let's declare a class named MyApp.MoreMath, extending MyApp.Math:

Ext.define('MyApp.MoreMath', {
extend: 'MyApp.Math',
statics: {
appName: 'MoreMath',
multiply: function(number1, number2) {
return number1 * number2;
}
},
constructor: function() {
this.callParent();
}
});

Note, we also declared (override) a static property called appName with a different value from the super class. Also note that when we instantiate, we call the super class constructor. In this case, this.statics().appName does a reference to the MyApp.Math.appName (which is Math) and the this.self.appName does a reference to the current object, which is MyApp.MoreMath.appName (with value equals to MoreMath).

Execute the following code:

var math1 = new MyApp.Math();
var math2 = new MyApp.Math();
var moreMath = new MyApp.MoreMath();

We will have the following output:

You instantiated the class: Math
App Name: Math
Count is: 1
You instantiated the class: Math
App Name: Math
Count is: 2
You instantiated the class: MoreMath
App Name: Math
Count is: 3

If you try to execute MyApp.MoreMath.sum(), you will get the error MyApp.MoreMath.sum is not a function. The static methods from superclass are not public in the subclass.

 

Migrating from Ext JS 3 to Ext JS 4


Ext JS 4 introduces major changes in its architecture, core system, and widgets. Most classes were refactored. We already know how the new class system works. We are going to introduce you to the new changes and new widgets. Also, there are some changes that are not compatible with Ext JS 3. To help you to migrate from Ext JS 3 to Ext JS 4, there are some tools that can help you.

Adapters

In previous versions of Ext JS, you were able to use Ext JS along with other third-party frameworks, such as jQuery, Prototype, and YUI, and Ext provided a special adapter so you could use these frameworks.

For example, if you want to use Ext along with jQuery, you have to import jQuery files, then ext-jquery-adapter.js, and then ext-all.js; only then would you be able to implement Ext code along with jQuery code, on the same page.

The following diagram illustrates how adapters worked until Ext JS 3:

In Ext JS 4, the adapter support has been discontinued. However, this does not mean you cannot use third-party libraries along with Ext JS anymore. They are no longer supported as base library dependencies for Ext JS, but you can still use them in addition to Ext JS files.

The following diagram illustrates how to use third-party libraries with Ext JS 4:

For example, until Ext JS 3, if we wanted to use jQuery along with Ext JS on the same page, this is how we would do it:

<script type="text/javascript" src="adapters/jquery.js"></script>
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/adapter/jquery/ext-jquery-adapter-debug.js"></script>
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/ext-all-debug.js"></script>

To keep compatibility with your legacy code is very simple; you have to remove the ext-jquery-adapter:

<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="../extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="adapters/jquery.js"></script>

JavaScript compatibility file

This JavaScript file contains the aliases and necessary overrides to make most of the Ext JS 3 code run under Ext JS 4.

You can use this file while you migrate all your Ext JS 3 code to Ext JS 4. It is recommended that you do not use this file as a permanent solution; use it only until you finish migrating to Ext JS 4.

Note

You can read how to properly use the JavaScript compatibility file inAppendix A,Ext JS 4 Versus Ext JS 3 Class Names.

Sandbox mode

Ext JS 4 is sandboxed, which means you can run Ext JS 4 alongside with previous versions of Ext JS on the same page.

The distributed release comes with the following sandbox mode files:

  • ext-all-sandbox.js

  • ext-all-sandbox-debug.js

  • ext-all-sandbox-dev.js

To use Ext JS 4 in the sandbox mode, you need to import the ext-all sandbox files and the ext-sandbox.css file as well. To make the Ext JS 4 code work along with code from previous versions, you need to alias the global Ext object to a different name (for example, Ext4) and it will be isolated from the previous version's code.

Let's say you have the following page implemented with Ext JS 3:

The following is the HTML code used to render the grid. As you can see, we are importing the default Ext JS 3 files ext-all.css and ext-all.js:

<html>
<head>
<title>Ext JS 3 + Ext JS 4 = sandbox</title>
<link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/ext-3.3.1/resources/css/ext-all.css" />
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/adapter/ext/ext-base-debug.js"></script>
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/ext-all-debug.js"></script>
<script type="text/javascript" src="sandbox/grid-ext3.js"></script>
</head>
<body>
<table border="1">
<tr>
<td>Ext JS 3 Grid</td>
</tr>
<tr>
<td><div id="grid3"></div></td>
</tr>
</table>
</body>
</html>

We are also importing the grid-ext3.js file, which contains the Ext JS 3 code to render the grid— a very simple grid:

Ext.onReady(function(){
// static data for the store
var myData = [
['Learning Ext JS', 'Packt', 'November 2008'],
['Learning Ext JS 3.2', 'Packt', 'October 2010'],
['Ext JS 3.0 Cookbook', 'Packt', 'October 2009'],
['Oracle Application Express 4.0 with Ext JS', 'Packt', 'March 2011']
];
// create the data store
var store = new Ext.data.ArrayStore({
fields: [
{name: 'book'},
{name: 'manufacturer'},
{name: 'published', type: 'date', dateFormat: 'F Y'},
]
});
// manually load local data
store.loadData(myData);
// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{
id :'book',
header : 'Book',
width : 250,
sortable : true,
dataIndex: 'book'
},
{
header : 'Manufacturer',
width : 75,
sortable : true,
dataIndex: 'manufacturer'
},
{
header : 'Published',
width : 100,
sortable : true,
renderer : Ext.util.Format.dateRenderer('F Y'),
dataIndex: 'published'
}
],
stripeRows: true,
height: 140,
width: 430,
title: 'Ext JS Books - Ext 3',
stateId: 'grid'
});
grid.render('grid3);
});

Now, we want to add another grid using Ext JS 4 on the same page, right besides the Ext JS 3 grid, because we want to take advantage of new features such as the Model (new class from the new data package). To make the HTML page support Ext JS 4, we have to add the sandbox mode files, instead of the default Ext JS 4 files (ext-all.css, ext-all.js, and ext-core.js):

<html>
<head>
<title>Ext JS 3 + Ext JS 4 = sandbox</title>
<link rel="stylesheet" type="text/css" href="http://extjs.cachefly.net/ext-3.3.1/resources/css/ext-all.css" />
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/adapter/ext/ext-base-debug.js"></script>
<script type="text/javascript" src="http://extjs.cachefly.net/ext-3.3.1/ext-all-debug.js"></script>
<script type="text/javascript" src="sandbox/grid-ext3.js"></script>
<link rel="stylesheet" type="text/css" href="../extjs/resources/css/ext-sandbox.css" />
<script type="text/javascript" src="../extjs/builds/ext-all-sandbox-debug.js"></script>
<script type="text/javascript" src="sandbox/grid-ext4.js"></script>
</head>
<body>
<table border="1">
<tr>
<td>Ext JS 3 Grid</td>
<td>Ext JS 4 Grid</td>
</tr>
<tr>
<td><div id="grid3"></div></td>
<td><div id="grid4"></div></td>
</tr>
</table>
</body>
</html>

The HTML page is now ready to support Ext JS 3 and Ext JS 4 on the same page. Let's take a look on the grid code made with Ext JS 4; we are going to put this code into the grid-ext4.js file:

Ext4.require([
'Ext.grid.*',
'Ext.data.*'
]);
Ext4.onReady(function(){
Ext4.regModel('Book', {
fields: [
{name: 'book'},
{name: 'manufacturer'},
{name: 'published', type: 'date', dateFormat: 'F Y'}
]
});
// Array data for the grids
Ext4.grid.dummyData = [
['Drupal 7 Module Development','Packt', 'December 2010'],
['PHP 5 Social Networking','Packt', 'October 2010'],
['Object-Oriented Programming with PHP5','Packt','December 2007'],
['Expert PHP 5 Tools','Packt','March 2010']
];
var store = new Ext4.data.ArrayStore({
model: 'Book',
data: Ext4.grid.dummyData
});
var grid2 = new Ext4.grid.GridPanel({
store: store,
columns: [
{text: "Book", width: 250, dataIndex: 'book'},
{text: "Manufacturer", width: 75, dataIndex: 'manufacturer'},
{text: "Published", width: 100, dataIndex: 'published',
renderer: Ext4.util.Format.dateRenderer('F Y')}
],
columnLines: true,
width: 430,
height: 140,
title: 'PHP Books - Ext 4',
renderTo: 'grid4'
});
});

Note

Note that we are not using Ext namespace, as we were in the Ext JS 3 code. Instead, we are using Ext4 namespace. An alias is required—you cannot use the same namespace (Ext); otherwise, your code will not work.

If you try to load the page, the following is the result you will get—Ext JS 3 and Ext JS 4 working together on the same page:

Note

Remember, it is recommended that you migrate all your code to Ext JS 4. This file can help you to add new Ext JS 4 functionalities into your legacy application, but it is not supposed to be used as a permanent solution.

Sencha platform

Ext JS always provided a class system and architecture of its own—component-oriented, with satellite packages for layout, state, utilities, and data. Ext JS 4 architecture looks much the same as Ext JS 3 architecture:

In 2010, Sencha was born and Ext JS got a new brother called Sencha Touch. Sencha Touch is a mobile JavaScript framework. Sencha Touch is to mobile devices, what Ext JS is for desktops. The Sencha Touch architecture is different from Ext JS 3 architecture. For the Ext JS 4 release, they decided to combine Sencha Touch's architecture with Ext JS's. So, the Sencha platform was born, providing some common code shared between Sencha Touch and Ext JS 4. This includes the data package, layouts, most of the utility functions, and the new charting and animation packages. This way, the Sencha team can provide stable code for a product and will be also available for others, creating and maintaining a stable platform. This is also an advantage for developers, because all the knowledge and experience with Ext JS can be easily channeled into developing mobile applications with Sencha Touch, and vice-versa. Plus, a large amount of code can be reused and also increase the community size for platform-based extensions by including web and mobile developers:

Data package

The data package is one of the packages that Ext JS 4 now shares with Sencha Touch. This package contains the classes that are responsible for loading and saving the data, and it has a large number of changes. Let's briefly discuss some of these changes:

  • Store is the class for which you no longer need to set the data format that you are loading on the Store; in other words, you do not need to specify if you are loading JSON or XML (JsonStore or XmlStore), as the Store will automatically detect the data format. The Store API is now capable of sorting and filtering, and the new Reader can read nested data from the server.

  • Model is a new class in Ext JS 4, similar to Record, with new capabilities. The new Model class supports associations and validations.

  • Proxy is the class responsible for loading and saving the data now, and it receives the Reader and Writer instances. You can attach the proxy to a Store or to a Model, so you don't need to use a Store anymore. There is a new proxy in Ext JS 4: LocalStorageProxy, and it persists the data into an HTML5 local storage. There is also a new proxy that persists the data into session storage.

These changes are not 100% backward-compatible. If you are migrating your code from Ext JS 3 to Ext JS 4, you will need to use the Ext JS 3 compatibility file, but you will still have to change some of your code.

We will take a deeper look at all the data package changes and how to use them in the next chapter.

Draw package and charts

Ext JS 4 introduces the new draw package, which provides custom drawing capabilities, based on HTML5 standards. We can draw basic shapes, such as squares, circles, and also texts. It also provides an engine to draw complex shapes using SVG paths. The new draw package is the base package for the new chart API.

Ext JS 3 introduced charts as newly-available components, but they required Flash to work. In Ext JS 4, you don't need Flash to use charts anymore; now, charts are completely javascript-driven. The charts now use SVG (Scalable Vector Graphics), Canvas, and VML (Vector Markup Language).

With Ext JS 4, you can plot any chart as desired; all charts are customizable. Some of the options are: Bar/Column, Line/Area, Scatter, Radar, or you can also mix any of these charts to create a customized one, according to your needs.

We will dive into the draw and chart packages in Chapter 4, Upgraded Charts.

Layouts

Layout is one of the most important and powerful features of Ext JS. In Ext 2, layouts were very fast, but not flexible enough. In Ext JS 3, the flexibility was improved, but it cost some performance. In Ext JS 4, the layout engine was rewritten and now it is faster and more flexible than ever. There are also some new layouts, such as DockLayout, ToolbarLayout, and FieldLayout.

We will take a closer look at the new layout in Chapter 3,Upgraded Layouts.

Grids

The grid is the widget that is most used for sure and it is one of the most important components of Ext JS. In Ext JS 4, the grid has been completely rewritten and now it is faster, easier to customize, and has better performance.

In Ext JS 3, when you wanted to display thousands of records in the grid without paging, you had to be very careful, because it was a very heavy rendering. The solution to this issue was to use a plugin to support buffering. In Ext JS 4, the grid natively supports buffering, and now you do not have to worry about this issue anymore.

Ext JS 4 also improved editing capability for grids. In Ext JS 3, if you wanted to use a grid to edit information, you would have to use the EditorGrid, a specialized grid, or a plugin called RowEditor. In Ext JS 4, there is an editing plugin that can be applied to any grid easily, and RowEditor has become a class component supported by the API; it is not an extension anymore.

In Ext JS 3, if you wanted to add any new functionality to a grid you would create a customized grid (create a new class extending the default grid component) or you would create a plugin, correct? Ext JS 4 introduces a new class called Ext.grid.Feature, which provides all the basic features to create new grid features. Now there is a standard way to create new grid functionalities and this makes the grid a more consistent component.

In previous Ext JS versions, when the page rendered the grid, it created an HTML markup to handle all the customizations the grid supported, such as editing, row expansion, and so on, even if you were not using these features. In Ext JS 4, there is a reduction of the HTML markup. Now it renders only what the grid is going to use, only the features you enabled, and this is a great performance boost, making the grid even faster and lighter than the ListView component (in Ext JS 3, the ListView is a lighter version of the grid, used only to visualize the information you display).

We will take a closer look at the Grid component, its new features, and how to use them in Chapter 5,Upgraded Grid, Tree, and Form.

Forms

Forms are another very used component in Ext JS. In Ext JS 4, there are some new features that are going to make our lives easier when configuring a form. The first update is that you can use any Layout within a form now. The FormLayout has been removed; it no longer exists.

Ext JS 4 introduces a new class called FieldContainer for managing layouts within forms. Now, you can add any component to a form, such as a grid. There is also a huge improvement in regards to validation.

We will take a closer look at forms, its new features, and how to use them, in Chapter 5,Upgraded Grid, Tree, and Form.

Accessibility

Making an application accessible using JavaScript is always difficult. Ext JS 4 introduces three new features that make it easy to do so:

  • Ext JS 4 comes with ARIA (Accessible Rich Internet Application) support. All components have attributes to support ARIA.

  • Ext JS 4 also supports keyboard navigation on any application.

  • There is a new theme with high contrast (dark background and text in a light color).

Theming

If you have already tried to customize a theme for Ext JS 3, you know how painful it can be. Theming in Ext JS 4 is much easier than in previous versions. You can change the color scheme for all components by changing a single variable. That is because Ext JS 4 themes use Sass and Compass, two powerful tools to create CSS easily. Any component can be easily customized now.

We will build and customize a new theme using Sass and Compass in Chapter 6,Ext JS 4 Themes.

 

Summary


In this chapter, we have covered the new Ext JS 4 SDK, learned how to use its new files, the new way to use adapters, and how to use Ext JS 3 (or older versions) along with Ext JS 4. We also covered a very quick overview of the new components and what has changed in the existing ones. We also learned how to use the overhauled documentation and how the packages are organized.

We learned, through examples, how to use the new features from the new class system—for example, how to define a class without using the new keyword; how to use mixins; the config declaration to auto generate methods, getters, and setters; the statics declaration; and how the dynamic class loading works.

In the next chapter, we will learn about the new Ext JS 4 data package—what has changed, what is new, and how to use it.

About the Author

  • Loiane Groner

    Loiane Groner has over 10 years of experience in developing enterprise applications. Currently, she works as a business analyst and a Java/HTML5/JavaScript developer at an American financial institution.

    She is passionate about technology, publishes articles on her blog, and has presented talks at conferences about Java, ExtJS, Cordova, Ionic, TypeScript and Angular.

    She is a Google Developer Expert in Web Technologies and Angular, and a Microsoft Most Valuable Professional in Visual Studio and Development Technologies. She has also authored other Packt books.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Access now