Sencha Inc. | HTML5 Apps

Ext JS Essentials

Published Nov 02, 2007 | Brian Moeskau | Tutorial | Easy
Last Updated Jul 11, 2011

This Tutorial is most relevant to Ext JS, 2.x, 3.x.

Anyone new to using the Ext library or trying to learn more about it has come to the right place. This tutorial will walk through Ext basic concepts and how to get a dynamic page up and running quickly. It is assumed that the reader has some Javascript experience and a basic understanding of the HTML document object model (DOM). If not, you may want to begin with some general references first.

Let's Get Started

Download Example File

We're going to walk through some of the most common tasks that people have to accomplish in Javascript and how to perform them using Ext. If you'd like to experiment as you go, you should download the starter files in which we will use to build up a page of working Ext code.

This zip contains four files: ExtStart.html, ExtStart.js, ExtStart.css and ajax-example.php.

  • Unzip all 4 files into a folder directly under the folder where Ext is installed (for example, if Ext is at "C:\code\ext-2.0\," create a new folder under "ext-2.0\" called "tutorial" ie. "C:\code\ext-2.0\tutorial\").
  • Double-click ExtStart.html so that it launches in your default web browser, and you should get a message telling you that everything is configured correctly. If you get a JavaScript error, please follow the instructions on that page to get it working.

Now you're ready to open ExtStart.js in your favorite IDE or text editor and take a look at it:

Ext.onReady(function() {
	alert("Congratulations!  You have Ext configured correctly!");

Ext.onReady is probably the first method that you'll use on every page. This method is automatically called once the DOM is fully loaded, guaranteeing that any page elements that you may want to reference will be available when the script runs. You can go ahead and delete the alert() line now so that we can start adding some real code that actually does something useful!

Element: The Heart of Ext

Almost everything you do in Javascript will at some point involve referencing specific elements on your page so that you can do interesting things with them. Using traditional Javascript, selecting a DOM node by ID is done like this:

var myDiv = document.getElementById('myDiv');

This works just fine, but the object that is returned (a DOM node) doesn't offer much in the way of power or convenience. In order to do anything useful with that node, you are left still writing a lot of custom plumbing code yourself. Plus it is your responsibility to handle all of the differences in how the node can be used from browser to browser, which can be daunting.

Enter the Ext.Element object. The Element really is the heart of Ext as most of what you'll do involves getting access to Elements and performing actions on them. The Element API is fundamental to the entire Ext library, and if you spend the time to really learn only one class in Ext well, Element should be it!

The corresponding code to get an Ext Element by ID looks like this (the starter page ExtStart.html contains a div with the id "myDiv," so go ahead and add this code to ExtStart.js):

Ext.onReady(function() {
	var myDiv = Ext.get('myDiv');

So we are getting back an Element object now—what's so interesting about that?

  • Element wraps most of the DOM methods and properties that you'll need, providing a convenient, unified, cross-browser DOM interface (and you can still get direct access to the underlying DOM node when you need it via Element.dom)
  • The Element.get() method provides internal caching, so multiple calls to retrieve the same object are incredibly fast
  • The most common actions performed on DOM nodes are built into direct, cross-browser Element methods (add/remove CSS classes, add/remove event handlers, positioning, sizing, animation, drag/drop, etc.)

This means that you can do all kinds of useful stuff with very minimal code. Here are just a few simple examples (see the Element API documentation for the complete list of everything that you can do). Go ahead and try adding some of these to ExtStart.js after the previous line where we got the 'myDiv' Element:

myDiv.highlight();      // The element's background will highlight to yellow then fade back
myDiv.addClass('red');  // Add a custom CSS class (defined in ExtStart.css);         // Center the element in the viewport
myDiv.setOpacity(.25);  // Make the element partially-transparent

Selecting DOM Nodes

Often it is either impractical or impossible to select DOM nodes by ID. Maybe the ID is not set, or you don't know it, or there are too many elements to practically reference directly by ID. Sometimes you may want to select nodes based on something other than ID, like an attribute or a CSS classname. For these reasons, Ext ships with an extremely powerful DOM selector library called DomQuery.

DomQuery can be used as a standalone library, but more often when using Ext, you'll use it in the context of selecting Elements so that you can then act on them via the Element interface. Luckily, the Element object itself supports querying via the method, which internally uses DomQuery to select elements. As a simple example of how you might use this, the ExtStart.html file contains several paragraph (<p>) tags, none of which have ids. If you wanted to easily select every paragraph and perform an action on all of them at once, you could do something like this:

// Highlights every paragraph'p').highlight();

This example demonstrates a very handy aspect of—it returns a CompositeElement, which provides access to every underlying Element via the Element interface. This allows you to easily act on every Element instance returned by without looping and touching each one individually.

DomQuery supports a wide array of selection options, including most of the W3C CSS3 DOM selectors, basic XPath, HTML attributes and a lot more. Please see the DomQuery API documentation for complete details on this powerful library.

Responding to Events

So far in our examples, all of the code we've written has been directly inside the onReady function, which means that it always executes immediately after the page loads. This doesn't give us much control—you will most commonly want your code to execute in response to specific actions or events that you choose to handle. To do this, you define event handlers that can respond to events using functions that you assign.

Let's start off with a simple example. Open up ExtStart.js and edit it so that your code looks like this:

Ext.onReady(function() {
    Ext.get('myButton').on('click', function(){
        alert("You clicked the button");

The code still executes when the page loads, but there's an important difference. The function containing the alert() is defined, but is not actually executed immediately—it is assigned as the "handler" of the button click event. Spelled out in plain English, this code might read: "Get a reference to the Element with id 'myButton' and assign a function to be called anytime someone clicks on the Element."

Not surprisingly, allows you to do the same thing, but with an entire group of Elements at once. For example, to show our message when any paragraph in our test page is clicked, we could do this:

Ext.onReady(function() {'p').on('click', function() {
		alert("You clicked a paragraph");

In these two examples, the event handling function is simply declared inline, without giving it a function name. The term for this type of function is an "anonymous function" since it is declared without ever being named. You can also assign an event to be handled by a named function, which is especially useful if you want to reuse the function and have it handle multiple events. For example, this code is functionally equivalent to the previous example:

Ext.onReady(function() {
    var paragraphClicked = function() {
      alert("You clicked a paragraph");
    }'p').on('click', paragraphClicked);

So far we have looked at performing a generic action when our event is raised, but how do we actually know which specific Element raised the event so that we can perform some action on it? It turns out to be pretty easy—the Element.on method passes three extremely useful parameters to the event handling function (we're only going to look at the first one here, but you should explore the API documentation to learn more about event handling details). In our previous examples our handling function was ignoring these parameters, but with one simple change, we can provide an additional level of functionality. The first, and most important, parameter is the event that occurred. This is actually an Ext.EventObject, which is both normalized across browsers and provides more information than the standard browser event. For example, the event's target DOM node can be retrieved with this simple addition:

Ext.onReady(function() {
	var paragraphClicked = function(e) {
	}'p').on('click', paragraphClicked);

Note that target is a DOM node, so we first retrieve the corresponding Element, then perform whatever action we want on it. In this case, we are visually highlighting the paragraph.

Passing Arguments to Event Handlers

Here's a quick example on how to pass arguments to an event handler using createDelegate:

var someHandler = function(evt,t,o,myArg1,myArg2,myArg3) {
        //do stuff
}'.notice-type1').addListener('click', someHandler.createDelegate(this, [4,'pizza',11], true));'.notice-type2').addListener('click', someHandler.createDelegate(this, [7,'stuff',12], true));

The function someHandler will get called with the following arguments:

evt, t, o
These are the arguments that would get passed to your event handler normally. They are: the EventObject describing the event, the Element which was the target of the event, and the options object from the addListener call. See addListener in the API for more information. You can also set a breakpoint in Firebug inside your event handler to check these objects out and see what kind of useful things they contain.
myArg1, myArg2, myArg3
your own custom arguments specified as an array which is passed as the second argument to createDelegate. In this case we're passing 4,'pizza',11 for elements of class "notice-type1" and 7,'stuff',12 for elements of class "notice-type2".

If all you want to do is pass custom arguments to the even handler and you don't need to have access to the element that fired the event you're probably better off just using createCallback.

See addListener and Function for more details.

Share this post:
Leave a reply

Written by Brian Moeskau

1 Comment

Markus Biacsics

4 years ago

Thx this site is very usefull.
But i can’t rebuild the last example

Leave a comment:

Commenting is not available in this channel entry.