HTML and ExtJS Components

If you have a background in creating websites with raw HTML then it's only a matter of time before you'll find yourself drowning in ExtJS components, knowing exactly what HTML you'd like to use but having absolutely no idea how to get ExtJS to create it. In this article we'll cover the main techniques at your disposal and attempt to answer the question: “How do I create some simple HTML with an ExtJS component?”.

Introduction

First let's tackle some common misconceptions.

  • If you've spent a lot of time working with other frameworks then you might fall into the trap of viewing an ExtJS component as little more than an abstraction for manipulating a DOM element. In other words, the DOM is king.
  • On the flip side, once you get a taste for components, it's easy to lose sight of the DOM altogether. You start seeing every rectangle in your UI as just another component and the DOM is irrelevant.

Interestingly, both extremes lead to similar mistakes, with simple tasks approached heavy-handedly and lots of components used to do a job where a single component would suffice. As you might expect, the reality lies somewhere between these two extremes. The DOM certainly isn't irrelevant but it's the components that are king.

First and foremost, a component is a JavaScript object. This object has many responsibilities, the most important of which is to create and manage DOM elements. Each component creates a single outermost element, known as el, and then adds any other elements it needs inside that el.

The parent-child relationship formed by a container and its items is reflected in their DOM elements. The main el for a component is always a descendant of the el for its parent container.

The initial creation of DOM elements by a component is a process known as rendering. The rendering process only happens once per component and is highly optimized to ensure that the rendering of a large component tree is as fast as possible.

It's not uncommon for a component to need to adjust its elements at some subsequent point, usually in response to user interaction. Often this is something as simple as adding a CSS class but a component can completely change its DOM structure if required. In general the only restriction is that the outer el must remain the same element, though some component types may impose much tighter restrictions.

The terms rendering and layout should not be confused. Layout is the process of positioning and sizing components and their elements. Unlike rendering, layout is not a one-off process and it is often necessary to re-run layouts when a component makes changes to its DOM elements.

Rendering a Component

Let's start with a really simple example to see what gets rendered by default.

        // The renderTo config option specifies a parent DOM element for rendering the component.
        // For brevity it is not shown in the remaining examples.
        new Ext.Component({
            renderTo: 'component-demo'
        });
    

The problem with this example is that it's so simple we can't actually see it.

However, it does have a presence in the DOM.

        <div id="component-1001" class="x-component x-component-default" role="presentation"></div>
    

Let's break that down.

  • A component renders as a single <div>. More sophisticated components may have multiple elements but there will always be a single, outermost element that acts as the primary element for the component. After a component is rendered you can access this element via the el property of the component.
  • The id attribute of the element matches the id of the component.
  • There are two CSS classes. These classes are derived from the baseCls and ui config options. These are advanced settings and are rarely used in client code. We will see an example of using baseCls later.
  • Depending on your ExtJS version you may see other attributes, such as an ARIA role.

When we discard the fluff we're left with something very simple:

        <div id="component-1001" ...></div>
    

Let's add a few more options and some CSS so that we can actually see the component.

        new Ext.Component({
            cls: 'green-box',
            height: 60,
            width: 300
        });
    
        .green-box {
            background-color: #fec;
            border: 2px solid #5a7;
            border-radius: 5px;
            box-shadow: 2px 2px 2px #bbb;
            padding: 5px;
        }
    

The three settings we've added translate pretty directly into the markup for our component's element:

        <div id="component-1001" class="green-box ..." style="height: 60px; width: 300px;" ...></div>
    

Using this as the basis for the examples that follow we can now start to add to our HTML.

The html Config Option

Dirty and direct, the html config option specifies a string of HTML content to be injected directly into the component.

        new Ext.Component({
            html: 'Some <b>HTML</b> content',
            ...
        });
    
        <div id="..." class="green-box x-component x-component-default" ...>
            Some <b>HTML</b> content
        </div>
    

For simple, static HTML the html config option does the job fine. The content can also be updated by passing a string of HTML to the update method.

        var summary = new Ext.Component({
            html: 'Some <b>content</b>',
            ...
        });

        new Ext.button.Button({
            ...

            handler: function() {
                summary.update('Some slightly different <b>content</b>');
            }
        });
    

However, the html config option only affects the component's content. If we want to customize the outer el itself then we'll need to use a different approach.

autoEl

To change the element name of the outer el we can use the autoEl config option:

        new Ext.Component({
            autoEl: 'form',
            ...
        });
    

It looks just the same as before but the markup has changed:

        <form id="..." class="green-box x-component x-component-default" ...></form>
    

The autoEl can also be used to change other aspects of a component's el by passing a config object rather than a string. For example, we can add other attributes or simple HTML content:

        new Ext.Component({
            autoEl: {
                href: 'javascript:alert(%22Clicked!%22)',
                html: 'Click Me!',
                tag: 'a'
            }
        });
    
        <a href="javascript:alert(%22Clicked!%22)" ...>Click Me!</a>
    

The autoEl config option is used as a DomHelper config so it accepts all the same options. e.g. Creating child elements via cn:

        new Ext.Component({
            ...

            autoEl: {
                cn: [
                    'Some ',
                    {tag: 'b', cn: 'HTML'},
                    ' content'
                ]
            }
        });
    
        <div ...>
            Some <b>HTML</b> content
        </div>
    

autoEl is fine as far as it goes but it has two key problems: it's difficult to parameterize and it isn't very human-readable once you start adding child elements. For richer content it's much easier to use templates.

tpl & data

The config options tpl and data work in tandem. tpl specifies a template (using XTemplate syntax) and the data is then applied to that template. It's common for the tpl to be specified at the class level and the data to vary between instances. However, in these simple examples we'll show them both specified at the instance level:

        new Ext.Component({
            ...

            tpl: '{name} is {age} years old and lives in {location}',

            data: {
                age: 26,
                location: 'Italy',
                name: 'Mario'
            }
        });
    
        <div ...>
            Mario is 26 years old and lives in Italy
        </div>
    

Much like with the html config option, the content can be updated using the update method. Instead of passing a string we pass a new data object, which is then applied to our template to generate the new content.

        var summary = new Ext.Component({
            ...

            tpl: '{name} is {age} years old and lives in {location}',

            data: {
                age: 26,
                location: 'Italy',
                name: 'Mario'
            }
        });

        new Ext.button.Button({
            ...

            handler: function() {
                summary.update({
                    age: 7,
                    location: 'Japan',
                    name: 'Aimee'
                });
            }
        });
    

XTemplates have a rich and powerful syntax that goes well beyond substituting data values. A full discussion of templates is beyond the scope of this article but the next example gives a sense of what's possible. It shows how to generate an HTML list using an array of values.

        new Ext.Component({
            ...

            data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],

            tpl: [
                '<ul>',
                    '<tpl for=".">',
                        '<li>{.}</li>',
                    '</tpl>',
                '</ul>'
            ]
        });
    

The HTML generated for this component is:

        <div ...>
            <ul>
                <li>London</li>
                <li>Paris</li>
                <li>Moscow</li>
                <li>New York</li>
                <li>Tokyo</li>
            </ul>
        </div>
    

Note that the <ul> is still wrapped in the component's main el. If we wanted to remove that <div> we could use the autoEl config described earlier to switch the el to a <ul> and remove the <ul> from the template.

        new Ext.Component({
            ...

            autoEl: 'ul',
            data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],

            tpl: [
                '<tpl for=".">',
                    '<li>{.}</li>',
                '</tpl>'
            ]
        });
    

HTML Encoding

XTemplates do not HTML encode values by default. However, it's easy to pass values through Ext.util.Format.htmlEncode from within a template:

        new Ext.Component({
            ...

            tpl: '<b>Email:</b> {email:htmlEncode}',

            data: {
                email: 'John <john@example.com>'
            }
        });
    

Without correct encoding, the email address inside the <...> would be lost.

targetEl

For more complex components, such as panels or windows, the HTML provided by the configuration options html and tpl isn't injected directly into the el. To ensure it doesn't overwrite the header or toolbars it's written to the body element instead.

        new Ext.panel.Panel({
            ...

            bodyPadding: 10,
            title: 'Title',
            tpl: 'Some <b>{lang}</b> content',

            data: {
                lang: 'HTML'
            }
        });
    

The element used for this purpose is known as the targetEl. We'll see how to change the targetEl for a custom component later.

Note that autoEl is still responsible for configuring the outer el, it isn't affected by the targetEl.

Recap

At this stage we're ready to answer our original question: “How do I create some simple HTML with an ExtJS component?”

  • Use autoEl to configure the outer element.
  • Use the html config to set simple HTML content.
  • Use tpl and data if you need something a little more dynamic.

However, creating the HTML is just the first part of the story. The next three sections introduce some common techniques for adding interactions to custom components.

Events

Let's add a click event to our component. The approach used here is quite naive but it is relatively easy to understand.

        var clickCmp = new Ext.Component({
            ...
            count: 0,
            html: 'Click Me',

            listeners: {
                // Add the listener to the component's main el
                el: {
                    click: function() {
                        clickCmp.count++;

                        clickCmp.update('Click count: ' + clickCmp.count);
                    }
                }
            }
        });
    

The key thing to notice is that the listener is being registered on the el rather than on the component. By default a component doesn't have a click listener so we can't listen for that directly.

There are several problems with this example, the most important of which is the way the click listener obtains a reference to the component. In general it just isn't practical to capture a reference in the closure like this.

A much tidier way to do this is to add the listener in an override of initEvents. In the following example we define a custom component class that supports a handler config for reacting to clicks:

        Ext.define('ClickComponent', {
            extend: 'Ext.Component',

            initEvents: function() {
                this.callParent();

                // Listen for click events on the component's el
                this.el.on('click', this.onClick, this);
            },

            onClick: function() {
                // Fire a click event on the component
                this.fireEvent('click', this);

                // Call the handler function if it exists
                Ext.callback(this.handler, this);
            }
        });
    

We might use it something like this:

        new ClickComponent({
            ...
            count: 0,
            html: 'Click Me',

            handler: function() {
                this.count++;
                this.update('Click count: ' + this.count);
            }
        });
    

In our onClick method we also fire a click event, though we aren't using it in this example. Note that this is an event fired on the component, in reaction to the event fired by the element. It's important to understand the difference between these two events.

Event Delegation

With a bit of event delegation and some CSS we can quickly add a bit of interactivity to the list example we saw earlier. This example is a lot more advanced so we'll need to dissect it a little.

        new Ext.Component({
            ...

            autoEl: 'ul',
            data: ['London', 'Paris', 'Moscow', 'New York', 'Tokyo'],

            listeners: {
                // Add the listener to the component's main el
                el: {
                    // Use a CSS class to filter the propagated clicks
                    delegate: '.list-row',

                    click: function(ev, li) {
                        // Toggle a CSS class on the li when it is clicked
                        Ext.fly(li).toggleCls('list-row-selected');
                    }
                }
            },

            tpl: [
                '<tpl for=".">',
                    '<li class="list-row">{.}</li>',
                '</tpl>'
            ]
        });
    
        .list-row {
            border: 1px solid #f90;
            border-radius: 5px;
            cursor: pointer;
            list-style: none outside;
            padding: 5px;
        }

        .list-row-selected {
            background-color: #f90;
        }
    

The markup looks like this:

        <ul id="..." ...>
            <li class="list-row">London</li>
            <li class="list-row">Paris</li>
            <li class="list-row">Moscow</li>
            <li class="list-row">New York</li>
            <li class="list-row">Tokyo</li>
        </ul>
    

When an <li> is clicked, the CSS class list-row-selected is added to it.

If you haven't used event delegation before then this example may be a bit overwhelming. We're adding a single click listener to the component's el, which is a <ul> in this example. However, we aren't interested in clicks on the <ul> itself, we're using event propagation to respond to clicks on the child <li> elements. We target these elements using the delegate config option. Theoretically we could just use the tag name as the delegate selector but in practice it's much more common to use a CSS class. Our <li> elements each have the class list-row so we can use that.

The setting delegate: '.list-row' has two effects:

  • Clicks that aren't on an <li class="list-row"> element, or one of its descendants, will be ignored.
  • The second argument passed to the listener function will be the <li> element. Even if our <li> had contained child elements, the element passed to the listener would still be the enclosing <li>.

This component could be refactored into a class using initEvents just like the previous example.

DataView

If we wanted to push this list example further we might switch to using a DataView instead. The class Ext.view.View, usually referred to as DataView, provides automatic binding to a store with functionality like selection built in.

A full explanation of DataViews is beyond the scope of this article but the following example shows how we might use a DataView to improve upon our list implementation.

        new Ext.view.View({
            ...

            autoEl: 'ul',
            itemSelector: '.list-row',
            overItemCls: 'list-row-over',
            selectedItemCls: 'list-row-selected',
            simpleSelect: true,

            // An ExtJS store or store config
            store: {
                data: [{city: 'London'}, ...],
                fields: ['city']
            },

            tpl: [
                '<tpl for=".">',
                    '<li class="list-row">{city}</li>',
                '</tpl>'
            ]
        });
    

The most important setting here is itemSelector. It has a role very similar to the delegate option we saw earlier. It allows the DataView to map the DOM elements back to their records in the store, so that clicking selects the correct record.

renderTpl and renderData

The config options renderTpl and renderData are similar to tpl and data except they are run just once, during the initial rendering of the component. While both templates are responsible for creating the component's inner markup, the elements created by the renderTpl can be thought of as being part of the component's own markup, rather than being part of its content.

For example, earlier we saw a tpl used with a panel. While the tpl was responsible for rendering the dynamic content of the panel, the Panel class also has a renderTpl. This renderTpl creates the scaffolding elements of the panel that hold the header, toolbars and body.

Whereas a tpl might be specified on either the class or an instance, the renderTpl is almost exclusively set on the class definition.

baseCls

The baseCls is at the heart of the styling for a component. It is not only added to the outer el but it is also used as a prefix for CSS classes added to the main child elements of a component. The creation of these elements and their CSS classes is usually performed in the renderTpl.

Several ExtJS components set their own baseCls. For example, button uses x-btn, panel uses x-panel and window uses x-window. While it is frequently used internally by the library, it is rarely appropriate to use it in application code. You should only set the baseCls if you want to build your component's CSS from scratch. For example, you might change the baseCls of a button if you want to completely remove the default styling.

Setting a baseCls requires extreme caution. A component may be relying on some CSS properties having particular values and changing them may prove troublesome, especially when you try to upgrade to a newer version of ExtJS. If you're just looking to make a small CSS change then consider using one of the myriad of other techniques that are available.

childEls

ExtJS components store direct references to some of their elements. This is usually so that they can be modified without having to find the relevant child element each time. Once rendered, all components have a property called el that holds their outermost element. The config option childEls is used to create similar references to other elements.

For example, a panel has two such properties, el and body. A button has several, including btnIconEl and btnInnerEl, which are used to update the button's icon and text respectively.

A consequence of storing these references is that these components cannot make arbitrary changes to their markup. The elements that are referenced cannot be removed when changes are made. As a result, it doesn't make sense for childEls to reference elements created by a tpl, they are almost always created by the renderTpl.

Within the renderTpl, the convention is to give each element an id which appends the name of its corresponding property to the id of the component. This allows the property to be created using a quick lookup immediately after rendering.

Putting It All Together

The following example is quite involved and combines several of the ideas we've seen previously to form a much more complete and sophisticated component. What we're looking to create is this:

We split the class definition into two parts. First, we create a fairly generic component that has a header and body region with the appropriate styling. Nothing in this class is specific to displaying the biography data.

        // Note: This is correct for ExtJS 4.1 and 4.2. This page
        //       uses 4.0 so requires a slightly modified version.
        Ext.define('TitledComponent', {
            extend: 'Ext.Component',

            baseCls: 'titled-component',
            childEls: ['body', 'headerEl'],

            renderTpl: [
                '<h4 id="{id}-headerEl" class="{baseCls}-header">{header:htmlEncode}</h4>',
                '<div id="{id}-body" class="{baseCls}-body">{% this.renderContent(out, values) %}</div>'
            ],

            getTargetEl: function() {
                return this.body;
            },

            // Override the default implementation to add in the header text
            initRenderData: function() {
                var data = this.callParent();

                // Add the header property to the renderData
                data.header = this.header;

                return data;
            },

            setHeader: function(header) {
                this.header = header;

                // The headerEl will only exist after rendering
                if (this.headerEl) {
                    this.headerEl.update(Ext.util.Format.htmlEncode(header));
                }
            }
        });
    

Next we define a subclass that is specifically tailored to displaying biographies:

        Ext.define('BiographyComponent', {
            extend: 'TitledComponent',
            xtype: 'biography',

            header: 'Biography',
            tpl: '{name} is {age:plural("year")} old and lives in {location}',

            // Override update to automatically set the date in the header
            update: function(data) {
                this.callParent(arguments);

                this.setHeader('Biography updated at ' + ...);
            }
        });
    

Then we create an instance, which only needs the data:

        var summary = new BiographyComponent({
            data: {
                age: 26,
                location: 'Italy',
                name: 'Mario'
            }
        });
    

Add a button to update the biography:

        new Ext.button.Button({
            ...

            handler: function() {
                // Update the body content via the tpl
                summary.update({
                    age: ...,
                    location: ...,
                    name: ...
                });
            }
        });
    

The generated HTML is really quite simple:

        <div id="biography-1035" class="titled-component ..." ...>
            <h4 id="biography-1035-headerEl" class="titled-component-header">Biography</h4>
            <div id="biography-1035-body" class="titled-component-body">Mario is ...</div>
        </div>
    

The CSS isn't very interesting but here it is anyway. The only thing worth noting is how the selectors are tied to the baseCls we specified on TitledComponent. There's nothing specific to BiographyComponent.

        .titled-component {
            background-color: #fec;
            border: 2px solid #5a7;
            border-radius: 5px;
            box-shadow: 2px 2px 2px #bbb;
            display: inline-block;
        }

        .titled-component-body {
            margin: 10px;
        }

        .titled-component-header {
            background-color: #5a7;
            color: #fff;
            font-weight: 700;
            margin: 0;
            padding: 5px 10px;
            text-align: center;
        }
    

We've already met most of it but let's blitz through those class definitions and see what's going on.

  • xtype: 'biography'. The xtype is automatically included as a prefix for the id of our component instance, which is biography-1035 in this example. This same id is used as the id for the outer el and we also use it twice in the renderTpl.
  • baseCls: 'titled-component'. This CSS class is added to the outer el. Also notice how it is used as a prefix for the CSS classes of the inner elements.
  • childEls: ['body', 'headerEl']. Properties referencing these two childEls are created immediately after rendering. The DOM elements are found using their ids. The body element is used in the method getTargetEl, whereas the headerEl can be seen in the method setHeader.
  • The values for the renderTpl come from initRenderData. The id and baseCls are included by default and we also add our header property.
  • Within the renderTpl is the magical incantation '{% this.renderContent(out, values) %}'. This needs to appear within the targetEl and is used to inject the component's content. In ExtJS 4.0 the targetEl would have been left empty in the template and the content would have been injected after the targetEl had been added to the DOM. That proved too slow so from ExtJS 4.1 onwards the content has been rendered directly by the template. If you wanted to extend a container it would be '{% this.renderContainer(out, values) %}' instead.
  • getTargetEl returns the body element created by the childEls config. This is required so that the update method of the component updates the correct element. This should not be confused with the update method that is called in setHeader, which is a method of the headerEl element, not the component.
  • setHeader updates the contents of the header. It is written in such a way that it could be called before or after the component is rendered.

Even if you never have to write a low-level component like this, understanding the techniques it uses should help you to get a better grasp on the ExtJS source code. The TitledComponent class uses patterns that are typical of the standard ExtJS components. The BiographyComponent class, in contrast, is much more typical of an application class.

-----