Clear Up
SharpKit Reference

Ext Namespace

Download SDK: SharpKit.ExtJs.zip

Classes

Name Description
AbstractComponent

NOTE This is a private utility class for internal use by the framework. Don't rely on its existence.

An abstract base class which provides shared methods for Components across the Sencha product line.

Please refer to sub class's documentation

AbstractComponentConfig
AbstractComponentEvents
AbstractManager

Base Manager class

AbstractManagerConfig
AbstractManagerEvents
AbstractPlugin

The AbstractPlugin class is the base class from which user-implemented plugins should inherit.

This class defines the essential API of plugins as used by Components by defining the following methods:

  • init : The plugin initialization method which the owning Component calls at Component initialization time.

    The Component passes itself as the sole parameter.

    Subclasses should set up bidirectional links between the plugin and its client Component here.

  • destroy : The plugin cleanup method which the owning Component calls at Component destruction time.

    Use this method to break links between the plugin and the Component and to free any allocated resources.

  • enable : The base implementation just sets the plugin's disabled flag to false

  • disable : The base implementation just sets the plugin's disabled flag to true

AbstractPluginConfig
AbstractPluginEvents
Action

An Action is a piece of reusable functionality that can be abstracted out of any particular component so that it can be usefully shared among multiple components. Actions let you share handlers, configuration options and UI updates across any components that support the Action interface (primarily Ext.toolbar.Toolbar, Ext.button.Button and Ext.menu.Menu components).

Use a single Action instance as the config object for any number of UI Components which share the same configuration. The Action not only supplies the configuration, but allows all Components based upon it to have a common set of methods called at once through a single call to the Action.

Any Component that is to be configured with an Action must also support the following methods:

  • setText(string)
  • setIconCls(string)
  • setDisabled(boolean)
  • setVisible(boolean)
  • setHandler(function)

This allows the Action to control its associated Components.

Example usage:

  
// Define the shared Action.  Each Component below will have the same
            // display text and icon, and will display the same message on click.
            var action = new Ext.Action({
            text: 'Do something',
            handler: function(){
            Ext.Msg.alert('Click', 'You did something.');
            },
            iconCls: 'do-something',
            itemId: 'myAction'
            });
            var panel = new Ext.panel.Panel({
            title: 'Actions',
            width: 500,
            height: 300,
            tbar: [
            // Add the Action directly to a toolbar as a menu button
            action,
            {
            text: 'Action Menu',
            // Add the Action to a menu as a text item
            menu: [action]
            }
            ],
            items: [
            // Add the Action to the panel body as a standard button
            new Ext.button.Button(action)
            ],
            renderTo: Ext.getBody()
            });
            // Change the text for all components using the Action
            action.setText('Something else');
            // Reference an Action through a container using the itemId
            var btn = panel.getComponent('myAction');
            var aRef = btn.baseAction;
            aRef.setText('New text');
            
ActionConfig
ActionEvents
Ajax

A singleton instance of an Ext.data.Connection. This class is used to communicate with your server side code. It can be used as follows:

  
    Ext.Ajax.request({
            url: 'page.php',
            params: {
            id: 1
            },
            success: function(response){
            var text = response.responseText;
            // process server response here
            }
            });
            

Default options for all requests can be set by changing a property on the Ext.Ajax class:

  
    Ext.Ajax.timeout = 60000; // 60 seconds
            

Any options specified in the request method for the Ajax request will override any defaults set on the Ext.Ajax class. In the code sample below, the timeout for the request will be 60 seconds.

  
    Ext.Ajax.timeout = 120000; // 120 seconds
            Ext.Ajax.request({
            url: 'page.aspx',
            timeout: 60000
            });
            

In general, this class will be used for all Ajax requests in your application. The main reason for creating a separate Ext.data.Connection is for a series of requests that share common settings that are different to all other requests in the application.

AjaxConfig
AjaxEvents
Array

A set of useful static methods to deal with arrays; provide missing methods for older browsers.

ArrayConfig
ArrayEvents
Base

The root of all classes created with Ext.define.

Ext.Base is the building block of all Ext classes. All classes in Ext inherit from Ext.Base. All prototype and static members of this class are inherited by all other classes.

BaseConfig
BaseEvents
Class

Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading features made available by Ext.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.

If you wish to create a class you should use Ext.define which aliases Ext.ClassManager.create to enable namespacing and dynamic dependency resolution.

Ext.Class is the factory and not the superclass of everything. For the base class that all Ext classes inherit from, see Ext.Base.

ClassConfig
ClassEvents
ClassManager

Ext.ClassManager manages all classes and handles mapping from string class name to actual class objects throughout the whole framework. It is not generally accessed directly, rather through these convenient shorthands:

  • Ext.define
  • Ext.create
  • Ext.widget
  • Ext.getClass
  • Ext.getClassName

Basic syntax:

  
    Ext.define(className, properties);
            

in which properties is an object represent a collection of properties that apply to the class. See create for more detailed instructions.

  
    Ext.define('Person', {
            name: 'Unknown',
            constructor: function(name) {
            if (name) {
            this.name = name;
            }
            },
            eat: function(foodType) {
            alert("I'm eating: " + foodType);
            return this;
            }
            });
            var aaron = new Person("Aaron");
            aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
            

Ext.Class has a powerful set of extensible pre-processors which takes care of everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.

Inheritance:

  
    Ext.define('Developer', {
            extend: 'Person',
            constructor: function(name, isGeek) {
            this.isGeek = isGeek;
            // Apply a method from the parent class' prototype
            this.callParent([name]);
            },
            code: function(language) {
            alert("I'm coding in: " + language);
            this.eat("Bugs");
            return this;
            }
            });
            var jacky = new Developer("Jacky", true);
            jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
            // alert("I'm eating: Bugs");
            

See Ext.Base.callParent for more details on calling superclass' methods

Mixins:

  
    Ext.define('CanPlayGuitar', {
            playGuitar: function() {
            alert("F#...G...D...A");
            }
            });
            Ext.define('CanComposeSongs', {
            composeSongs: function() { ... }
            });
            Ext.define('CanSing', {
            sing: function() {
            alert("I'm on the highway to hell...")
            }
            });
            Ext.define('Musician', {
            extend: 'Person',
            mixins: {
            canPlayGuitar: 'CanPlayGuitar',
            canComposeSongs: 'CanComposeSongs',
            canSing: 'CanSing'
            }
            })
            Ext.define('CoolPerson', {
            extend: 'Person',
            mixins: {
            canPlayGuitar: 'CanPlayGuitar',
            canSing: 'CanSing'
            },
            sing: function() {
            alert("Ahem....");
            this.mixins.canSing.sing.call(this);
            alert("[Playing guitar at the same time...]");
            this.playGuitar();
            }
            });
            var me = new CoolPerson("Jacky");
            me.sing(); // alert("Ahem...");
            // alert("I'm on the highway to hell...");
            // alert("[Playing guitar at the same time...]");
            // alert("F#...G...D...A");
            

Config:

  
    Ext.define('SmartPhone', {
            config: {
            hasTouchScreen: false,
            operatingSystem: 'Other',
            price: 500
            },
            isExpensive: false,
            constructor: function(config) {
            this.initConfig(config);
            },
            applyPrice: function(price) {
            this.isExpensive = (price > 500);
            return price;
            },
            applyOperatingSystem: function(operatingSystem) {
            if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
            return 'Other';
            }
            return operatingSystem;
            }
            });
            var iPhone = new SmartPhone({
            hasTouchScreen: true,
            operatingSystem: 'iOS'
            });
            iPhone.getPrice(); // 500;
            iPhone.getOperatingSystem(); // 'iOS'
            iPhone.getHasTouchScreen(); // true;
            iPhone.hasTouchScreen(); // true
            iPhone.isExpensive; // false;
            iPhone.setPrice(600);
            iPhone.getPrice(); // 600
            iPhone.isExpensive; // true;
            iPhone.setOperatingSystem('AlienOS');
            iPhone.getOperatingSystem(); // 'Other'
            

Statics:

  
    Ext.define('Computer', {
            statics: {
            factory: function(brand) {
            // 'this' in static methods refer to the class itself
            return new this(brand);
            }
            },
            constructor: function() { ... }
            });
            var dellComputer = Computer.factory('Dell');
            

Also see Ext.Base.statics and Ext.Base.self for more details on accessing static properties within class methods

ClassManagerConfig
ClassManagerEvents
Component

Base class for all Ext components.

The Component base class has built-in support for basic hide/show and enable/disable and size control behavior.

xtypes

Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the xtype like getXType and isXType. See the Component Guide for more information on xtypes and the Component hierarchy.

Finding components

All Components are registered with the Ext.ComponentManager on construction so that they can be referenced at any time via Ext.getCmp, passing the id.

Additionally the Ext.ComponentQuery provides a CSS-selectors-like way to look up components by their xtype and many other attributes. For example the following code will find all textfield components inside component with id: 'myform':

  
    Ext.ComponentQuery.query('#myform textfield');
            

Extending Ext.Component

All subclasses of Component may participate in the automated Ext component lifecycle of creation, rendering and destruction which is provided by the Container class. Components may be added to a Container through the items config option at the time the Container is created, or they may be added dynamically via the add method.

All user-developed visual widgets that are required to participate in automated lifecycle and size management should subclass Component.

See the Creating new UI controls chapter in Component Guide for details on how and to either extend or augment Ext JS base classes to create custom Components.

The Ext.Component class by itself

Usually one doesn't need to instantiate the Ext.Component class. There are subclasses which implement specialized use cases, covering most application needs. However it is possible to instantiate a base Component, and it can be rendered to document, or handled by layouts as the child item of a Container:

  
    Ext.create('Ext.Component', {
            html: 'Hello world!',
            width: 300,
            height: 200,
            padding: 20,
            style: {
            color: '#FFFFFF',
            backgroundColor:'#000000'
            },
            renderTo: Ext.getBody()
            });
            

The Component above creates its encapsulating div upon render, and use the configured HTML as content. More complex internal structure may be created using the renderTpl configuration, although to display database-derived mass data, it is recommended that an ExtJS data-backed Component such as a View, GridPanel, or TreePanel be used.

ComponentConfig
ComponentEvents
ComponentLoader

This class is used to load content via Ajax into a Ext.Component. In general this class will not be instanced directly, rather a loader configuration will be passed to the constructor of the Ext.Component.

HTML Renderer

By default, the content loaded will be processed as raw html. The response text from the request is taken and added to the component. This can be used in conjunction with the scripts option to execute any inline scripts in the resulting content. Using this renderer has the same effect as passing the Ext.Component.html configuration option.

Data Renderer

This renderer allows content to be added by using JSON data and a Ext.XTemplate. The content received from the response is passed to the Ext.Component.update method. This content is run through the attached Ext.Component.tpl and the data is added to the Component. Using this renderer has the same effect as using the Ext.Component.data configuration in conjunction with a Ext.Component.tpl.

Component Renderer

This renderer can only be used with a Ext.container.Container and subclasses. It allows for Components to be loaded remotely into a Container. The response is expected to be a single/series of Ext.Component configuration objects. When the response is received, the data is decoded and then passed to Ext.container.Container.add. Using this renderer has the same effect as specifying the Ext.container.Container.items configuration on a Container.

Custom Renderer

A custom function can be passed to handle any other special case, see the renderer option.

Example Usage

  
var cmp = Ext.create('Ext.Component', {
            renderTo: Ext.getBody(),
            tpl: '{firstName} - {lastName}',
            loader: {
            url: 'myPage.php',
            renderer: 'data',
            params: {
            userId: 1
            }
            }
            });
            // call the loader manually (or use autoLoad:true instead)
            cmp.getLoader().load();
            
ComponentLoaderConfig
ComponentLoaderEvents
ComponentManager

Provides a registry of all Components (instances of Ext.Component or any subclass thereof) on a page so that they can be easily accessed by componentid (see get, or the convenience method Ext.getCmp).

This object also provides a registry of available Component classes indexed by a mnemonic code known as the Component's xtype. The xtype provides a way to avoid instantiating child Components when creating a full, nested config object for a complete Ext page.

A child Component may be specified simply as a config object as long as the correct xtype is specified so that if and when the Component needs rendering, the correct type can be looked up for lazy instantiation.

For a list of all available xtypes, see Ext.Component.

ComponentManagerConfig
ComponentManagerEvents
ComponentQuery

Provides searching of Components within Ext.ComponentManager (globally) or a specific Ext.container.Container on the document with a similar syntax to a CSS selector.

Components can be retrieved by using their xtype

  • component
  • gridpanel

Matching by xtype matches inherited types, so in the following code, the previous field of any type which inherits from TextField will be found:

  
prevField = myField.previousNode('textfield');
            

To match only the exact type, pass the "shallow" flag (See AbstractComponent's isXType method)

  
prevTextField = myField.previousNode('textfield(true)');
            

An itemId or id must be prefixed with a #

  • #myContainer

Attributes must be wrapped in brackets

  • component[autoScroll]
  • panel[title="Test"]

Member expressions from candidate Components may be tested. If the expression returns a truthy value, the candidate Component will be included in the query:

  
var disabledFields = myFormPanel.query("{isDisabled()}");
            

Pseudo classes may be used to filter results in the same way as in DomQuery:

  
// Function receives array and returns a filtered array.
            Ext.ComponentQuery.pseudos.invalid = function(items) {
            var i = 0, l = items.length, c, result = [];
            for (; i < l; i++) {
            if (!(c = items[i]).isValid()) {
            result.push(c);
            }
            }
            return result;
            };
            var invalidFields = myFormPanel.query('field:invalid');
            if (invalidFields.length) {
            invalidFields[0].getEl().scrollIntoView(myFormPanel.body);
            for (var i = 0, l = invalidFields.length; i < l; i++) {
            invalidFields[i].getEl().frame("red");
            }
            }
            

Default pseudos include:

  • not
  • first
  • last

Queries return an array of components. Here are some example queries.

  
// retrieve all Ext.Panels in the document by xtype
            var panelsArray = Ext.ComponentQuery.query('panel');
            // retrieve all Ext.Panels within the container with an id myCt
            var panelsWithinmyCt = Ext.ComponentQuery.query('#myCt panel');
            // retrieve all direct children which are Ext.Panels within myCt
            var directChildPanel = Ext.ComponentQuery.query('#myCt > panel');
            // retrieve all grids and trees
            var gridsAndTrees = Ext.ComponentQuery.query('gridpanel, treepanel');
            

For easy access to queries based from a particular Container see the Ext.container.Container.query, Ext.container.Container.down and Ext.container.Container.child methods. Also see Ext.Component.up.

ComponentQueryConfig
ComponentQueryEvents
Date

A set of useful static methods to deal with date Note that if Ext.Date is required and loaded, it will copy all methods / properties to this object for convenience

The date parsing and formatting syntax contains a subset of PHP's date() function, and the formats that are supported will provide results equivalent to their PHP versions.

The following is a list of all currently supported formats:

            Format  Description                                                               Example returned values
            ------  -----------------------------------------------------------------------   -----------------------
            d     Day of the month, 2 digits with leading zeros                             01 to 31
            D     A short textual representation of the day of the week                     Mon to Sun
            j     Day of the month without leading zeros                                    1 to 31
            l     A full textual representation of the day of the week                      Sunday to Saturday
            N     ISO-8601 numeric representation of the day of the week                    1 (for Monday) through 7 (for Sunday)
            S     English ordinal suffix for the day of the month, 2 characters             st, nd, rd or th. Works well with j
            w     Numeric representation of the day of the week                             0 (for Sunday) to 6 (for Saturday)
            z     The day of the year (starting from 0)                                     0 to 364 (365 in leap years)
            W     ISO-8601 week number of year, weeks starting on Monday                    01 to 53
            F     A full textual representation of a month, such as January or March        January to December
            m     Numeric representation of a month, with leading zeros                     01 to 12
            M     A short textual representation of a month                                 Jan to Dec
            n     Numeric representation of a month, without leading zeros                  1 to 12
            t     Number of days in the given month                                         28 to 31
            L     Whether it's a leap year                                                  1 if it is a leap year, 0 otherwise.
            o     ISO-8601 year number (identical to (Y), but if the ISO week number (W)    Examples: 1998 or 2004
            belongs to the previous or next year, that year is used instead)
            Y     A full numeric representation of a year, 4 digits                         Examples: 1999 or 2003
            y     A two digit representation of a year                                      Examples: 99 or 03
            a     Lowercase Ante meridiem and Post meridiem                                 am or pm
            A     Uppercase Ante meridiem and Post meridiem                                 AM or PM
            g     12-hour format of an hour without leading zeros                           1 to 12
            G     24-hour format of an hour without leading zeros                           0 to 23
            h     12-hour format of an hour with leading zeros                              01 to 12
            H     24-hour format of an hour with leading zeros                              00 to 23
            i     Minutes, with leading zeros                                               00 to 59
            s     Seconds, with leading zeros                                               00 to 59
            u     Decimal fraction of a second                                              Examples:
            (minimum 1 digit, arbitrary number of digits allowed)                     001 (i.e. 0.001s) or
            100 (i.e. 0.100s) or
            999 (i.e. 0.999s) or
            999876543210 (i.e. 0.999876543210s)
            O     Difference to Greenwich time (GMT) in hours and minutes                   Example: +1030
            P     Difference to Greenwich time (GMT) with colon between hours and minutes   Example: -08:00
            T     Timezone abbreviation of the machine running the code                     Examples: EST, MDT, PDT ...
            Z     Timezone offset in seconds (negative if west of UTC, positive if east)    -43200 to 50400
            c     ISO 8601 date
            Notes:                                                                    Examples:
            1) If unspecified, the month / day defaults to the current month / day,   1991 or
            the time defaults to midnight, while the timezone defaults to the      1992-10 or
            browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
            and minutes. The "T" delimiter, seconds, milliseconds and timezone     1994-08-19T16:20+01:00 or
            are optional.                                                          1995-07-18T17:21:28-02:00 or
            2) The decimal fraction of a second, if specified, must contain at        1996-06-17T18:22:29.98765+03:00 or
            least 1 digit (there is no limit to the maximum number                 1997-05-16T19:23:30,12345-0400 or
            of digits allowed), and may be delimited by either a '.' or a ','      1998-04-15T20:24:31.2468Z or
            Refer to the examples on the right for the various levels of              1999-03-14T20:24:32Z or
            date-time granularity which are supported, or see                         2000-02-13T21:25:33
            http://www.w3.org/TR/NOTE-datetime for more info.                         2001-01-12 22:26:34
            U     Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)                1193432466 or -2138434463
            MS    Microsoft AJAX serialized dates                                           \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
            \/Date(1238606590509+0800)\/
            

Example usage (note that you must escape format specifiers with '\' to render them as character literals):

  
// Sample date:
            // 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
            var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
            console.log(Ext.Date.format(dt, 'Y-m-d'));                          // 2007-01-10
            console.log(Ext.Date.format(dt, 'F j, Y, g:i a'));                  // January 10, 2007, 3:05 pm
            console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
            

Here are some standard date/time patterns that you might find helpful. They are not part of the source of Ext.Date, but to use them you can simply copy this block of code into any script that is included after Ext.Date and they will also become globally available on the Date object. Feel free to add or remove patterns as needed in your code.

  
Ext.Date.patterns = {
            ISO8601Long:"Y-m-d H:i:s",
            ISO8601Short:"Y-m-d",
            ShortDate: "n/j/Y",
            LongDate: "l, F d, Y",
            FullDateTime: "l, F d, Y g:i:s A",
            MonthDay: "F d",
            ShortTime: "g:i A",
            LongTime: "g:i:s A",
            SortableDateTime: "Y-m-d\\TH:i:s",
            UniversalSortableDateTime: "Y-m-d H:i:sO",
            YearMonth: "F, Y"
            };
            

Example usage:

  
var dt = new Date();
            console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
            

Developer-written, custom formats may be used by supplying both a formatting and a parsing function which perform to specialized requirements. The functions are stored in parseFunctions and formatFunctions.

DateConfig
DateEvents
DomHelper

The DomHelper class provides a layer of abstraction from DOM and transparently supports creating elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates from your DOM building code.

DomHelper element specification object

A specification object is used when creating elements. Attributes of this object are assumed to be element attributes, except for 4 special attributes:

  • tag - The tag name of the element.
  • children or cn - An array of the same kind of element definition objects to be created and appended. These can be nested as deep as you want.
  • cls - The class attribute of the element. This will end up being either the "class" attribute on a HTML fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM.
  • html - The innerHTML for the element.

NOTE: For other arbitrary attributes, the value will currently not be automatically HTML-escaped prior to building the element's HTML string. This means that if your attribute value contains special characters that would not normally be allowed in a double-quoted attribute value, you must manually HTML-encode it beforehand (see Ext.String.htmlEncode) or risk malformed HTML being created. This behavior may change in a future release.

Insertion methods

Commonly used insertion methods:

  • append
  • insertBefore
  • insertAfter
  • overwrite
  • createTemplate
  • insertHtml

Example

This is an example, where an unordered list with 3 children items is appended to an existing element with id 'my-div':

  
var dh = Ext.DomHelper; // create shorthand alias
            // specification object
            var spec = {
            id: 'my-ul',
            tag: 'ul',
            cls: 'my-list',
            // append children after creating
            children: [     // may also specify 'cn' instead of 'children'
            {tag: 'li', id: 'item0', html: 'List Item 0'},
            {tag: 'li', id: 'item1', html: 'List Item 1'},
            {tag: 'li', id: 'item2', html: 'List Item 2'}
            ]
            };
            var list = dh.append(
            'my-div', // the context element 'my-div' can either be the id or the actual node
            spec      // the specification object
            );
            

Element creation specification parameters in this class may also be passed as an Array of specification objects. This can be used to insert multiple sibling nodes into an existing container very efficiently. For example, to add more list items to the example above:

  
dh.append('my-ul', [
            {tag: 'li', id: 'item3', html: 'List Item 3'},
            {tag: 'li', id: 'item4', html: 'List Item 4'}
            ]);
            

Templating

The real power is in the built-in templating. Instead of creating or appending any elements, createTemplate returns a Template object which can be used over and over to insert new elements. Revisiting the example above, we could utilize templating this time:

  
// create the node
            var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
            // get template
            var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
            for(var i = 0; i < 5, i++){
            tpl.append(list, [i]); // use template to append to the actual node
            }
            

An example using a template:

  
var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
            var tpl = new Ext.DomHelper.createTemplate(html);
            tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed's Site"]);
            tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin's Site"]);
            

The same example using named parameters:

  
var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
            var tpl = new Ext.DomHelper.createTemplate(html);
            tpl.append('blog-roll', {
            id: 'link1',
            url: 'http://www.edspencer.net/',
            text: "Ed's Site"
            });
            tpl.append('blog-roll', {
            id: 'link2',
            url: 'http://www.dustindiaz.com/',
            text: "Dustin's Site"
            });
            

Compiling Templates

Templates are applied using regular expressions. The performance is great, but if you are adding a bunch of DOM elements using the same template, you can increase performance even further by "compiling" the template. The way "compile()" works is the template is parsed and broken up at the different variable points and a dynamic function is created and eval'ed. The generated function performs string concatenation of these parts and the passed variables instead of using regular expressions.

  
var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
            var tpl = new Ext.DomHelper.createTemplate(html);
            tpl.compile();
            //... use template like normal
            

Performance Boost

DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead of DOM can significantly boost performance.

Element creation specification parameters may also be strings. If useDom is false, then the string is used as innerHTML. If useDom is true, a string specification results in the creation of a text node. Usage:

  
    Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
            
DomHelperConfig
DomHelperEvents
Editor

The Editor class is used to provide inline editing for elements on the page. The editor is backed by a Ext.form.field.Field that will be displayed to edit the underlying content. The editor is a floating Component, when the editor is shown it is automatically aligned to display over the top of the bound element it is editing. The Editor contains several options for how to handle key presses:

  • completeOnEnter
  • cancelOnEsc
  • swallowKeys

It also has options for how to use the value once the editor has been activated:

  • revertInvalid
  • ignoreNoChange
  • updateEl

Sample usage:

  
var editor = new Ext.Editor({
            updateEl: true, // update the innerHTML of the bound element when editing completes
            field: {
            xtype: 'textfield'
            }
            });
            var el = Ext.get('my-text'); // The element to 'edit'
            editor.startEdit(el); // The value of the field will be taken as the innerHTML of the element.
            

EditorConfig
EditorEvents
ElementLoader

A class used to load remote content to an Element. Sample usage:

  
    Ext.get('el').load({
            url: 'myPage.php',
            scripts: true,
            params: {
            id: 1
            }
            });
            

In general this class will not be instanced directly, rather the Ext.Element.load method will be used.

ElementLoaderConfig
ElementLoaderEvents
Error

A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling errors in an Ext application. When you use Ext.Error to raise an error from within any class that uses the Ext 4 class system, the Error class can automatically add the source class and method from which the error was raised. It also includes logic to automatically log the eroor to the console, if available, with additional metadata about the error. In all cases, the error will always be thrown at the end so that execution will halt.

Ext.Error also offers a global error handling method that can be overridden in order to handle application-wide errors in a single spot. You can optionally ignore errors altogether, although in a real application it's usually a better idea to override the handling function and perform logging or some other method of reporting the errors in a way that is meaningful to the application.

At its simplest you can simply raise an error as a simple string from within any code:

Example usage:

  
    Ext.Error.raise('Something bad happened!');
            

If raised from plain JavaScript code, the error will be logged to the console (if available) and the message displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add additional metadata about the error being raised. The raise method can also take a config object. In this form the msg attribute becomes the error description, and any other data added to the config gets added to the error object and, if the console is available, logged to the console for inspection.

Example usage:

  
    Ext.define('Ext.Foo', {
            doSomething: function(option){
            if (someCondition === false) {
            Ext.Error.raise({
            msg: 'You cannot do that!',
            option: option,   // whatever was passed into the method
            'error code': 100 // other arbitrary info
            });
            }
            }
            });
            

If a console is available (that supports the console.dir function) you'll see console output like:

  
An error was raised with the following data:
            option:         Object { foo: "bar"}
            foo:        "bar"
            error code:     100
            msg:            "You cannot do that!"
            sourceClass:   "Ext.Foo"
            sourceMethod:  "doSomething"
            uncaught exception: You cannot do that!
            

As you can see, the error will report exactly where it was raised and will include as much information as the raising code can usefully provide.

If you want to handle all application errors globally you can simply override the static handle method and provide whatever handling logic you need. If the method returns true then the error is considered handled and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.

Example usage:

  
    Ext.Error.handle = function(err) {
            if (err.someProperty == 'NotReallyAnError') {
            // maybe log something to the application here if applicable
            return true;
            }
            // any non-true return value (including none) will cause the error to be thrown
            }
            
ErrorConfig
ErrorEvents
EventManager

Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides several useful events directly. See Ext.EventObject for more details on normalized event objects.

EventManagerConfig
EventManagerEvents
EventObject

Just as Ext.Element wraps around a native DOM node, Ext.EventObject wraps the browser's native event-object normalizing cross-browser differences, such as which mouse button is clicked, keys pressed, mechanisms to stop event-propagation along with a method to prevent default actions from taking place.

For example:

  
function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
            e.preventDefault();
            var target = e.getTarget(); // same as t (the target HTMLElement)
            ...
            }
            var myDiv = Ext.get("myDiv");  // get reference to an Ext.Element
            myDiv.on(         // 'on' is shorthand for addListener
            "click",      // perform an action on click of myDiv
            handleClick   // reference to the action handler
            );
            // other methods to do the same:
            Ext.EventManager.on("myDiv", 'click', handleClick);
            Ext.EventManager.addListener("myDiv", 'click', handleClick);
            
EventObjectConfig
EventObjectEvents
ExtContext

The Ext namespace (global object) encapsulates all classes, singletons, and utility methods provided by Sencha's libraries.

Most user interface Components are at a lower level of nesting in the namespace, but many common utility functions are provided as direct properties of the Ext namespace.

Also many frequently used methods from other classes are provided as shortcuts within the Ext namespace. For example Ext.getCmp aliases Ext.ComponentManager.get.

Many applications are initiated with Ext.onReady which is called once the DOM is ready. This ensures all scripts have been loaded, preventing dependency issues. For example:

  
    Ext.onReady(function(){
            new Ext.Component({
            renderTo: document.body,
            html: 'DOM ready!'
            });
            });
            

For more information about how to use the Ext classes, see:

  • The Learning Center
  • The FAQ
  • The forums
ExtContextConfig
ExtContextEvents
FocusManager

The FocusManager is responsible for globally:

  1. Managing component focus
  2. Providing basic keyboard navigation
  3. (optional) Provide a visual cue for focused components, in the form of a focus ring/frame.

To activate the FocusManager, simply call Ext.FocusManager.enable();. In turn, you may deactivate the FocusManager by subsequently calling Ext.FocusManager.disable();. The FocusManager is disabled by default.

To enable the optional focus frame, pass true or {focusFrame: true} to enable.

Another feature of the FocusManager is to provide basic keyboard focus navigation scoped to any Ext.container.Container that would like to have navigation between its child Ext.Component's.

FocusManagerConfig
FocusManagerEvents
Function

A collection of useful static methods to deal with function callbacks

FunctionConfig
FunctionEvents
Img

Simple helper class for easily creating image components. This renders an image tag to the DOM with the configured src.

Example usage:

  
var changingImage = Ext.create('Ext.Img', {
            src: 'http://www.sencha.com/img/20110215-feat-html5.png',
            renderTo: Ext.getBody()
            });
            // change the src of the image programmatically
            changingImage.setSrc('http://www.sencha.com/img/20110215-feat-perf.png');
            

By default, only an img element is rendered and that is this component's primary element. If the Ext.AbstractComponent.autoEl property is other than 'img' (the default), the a child img element will be added to the primary element. This can be used to create a wrapper element around the img.

Wrapping the img in a div:

  
var wrappedImage = Ext.create('Ext.Img', {
            src: 'http://www.sencha.com/img/20110215-feat-html5.png',
            autoEl: 'div', // wrap in a div
            renderTo: Ext.getBody()
            });
            
ImgConfig
ImgEvents
is

Determines information about the current platform the application is running on.

isConfig
isEvents
JSON

Modified version of Douglas Crockford's JSON.js that doesn't mess with the Object prototype.

JSONConfig
JSONEvents
Layer

An extended Ext.Element object that supports a shadow and shim, constrain to viewport and automatic maintaining of shadow/shim positions.

LayerConfig
LayerEvents
Loader

Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used via the Ext.require shorthand. Ext.Loader supports both asynchronous and synchronous loading approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:

Asynchronous Loading

  • Advantages:

    • Cross-domain
    • No web server needed: you can run the application via the file system protocol (i.e:
      file://path/to/your/index
                  .html
      )
    • Best possible debugging experience: error messages come with the exact file name and line number
  • Disadvantages:

    • Dependencies need to be specified before-hand

Method 1: Explicitly include what you need:

  
// Syntax
            Ext.require({String/Array} expressions);
            // Example: Single alias
            Ext.require('widget.window');
            // Example: Single class name
            Ext.require('Ext.window.Window');
            // Example: Multiple aliases / class names mix
            Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
            // Wildcards
            Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
            

Method 2: Explicitly exclude what you don't need:

  
// Syntax: Note that it must be in this chaining format.
            Ext.exclude({String/Array} expressions)
            .require({String/Array} expressions);
            // Include everything except Ext.data.*
            Ext.exclude('Ext.data.*').require('*');
            // Include all widgets except widget.checkbox*,
            // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
            Ext.exclude('widget.checkbox*').require('widget.*');
            

Synchronous Loading on Demand

  • Advantages:

    • There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js before
  • Disadvantages:

    • Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
    • Must be from the same domain due to XHR restriction
    • Need a web server, same reason as above

There's one simple rule to follow: Instantiate everything with Ext.create instead of the new keyword

  
    Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
            Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
            Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
            

Behind the scene, Ext.ClassManager will automatically check whether the given class name / alias has already existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given class and all its dependencies.

Hybrid Loading - The Best of Both Worlds

It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:

Step 1: Start writing your application using synchronous approach.

Ext.Loader will automatically fetch all dependencies on demand as they're needed during run-time. For example:

  
    Ext.onReady(function(){
            var window = Ext.widget('window', {
            width: 500,
            height: 300,
            layout: {
            type: 'border',
            padding: 5
            },
            title: 'Hello Dialog',
            items: [{
            title: 'Navigation',
            collapsible: true,
            region: 'west',
            width: 200,
            html: 'Hello',
            split: true
            }, {
            title: 'TabPanel',
            region: 'center'
            }]
            });
            window.show();
            })
            

Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:

  
[Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
            ClassManager.js:432
            [Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
            

Simply copy and paste the suggested code above Ext.onReady, i.e:

  
    Ext.require('Ext.window.Window');
            Ext.require('Ext.layout.container.Border');
            Ext.onReady(...);
            

Everything should now load via asynchronous mode.

Deployment

It's important to note that dynamic loading should only be used during development on your local machines. During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes the whole process of transitioning from / to between development / maintenance and production as easy as possible. Internally Ext.Loader.history maintains the list of all dependencies your application needs in the exact loading sequence. It's as simple as concatenating all files in this array into one, then include it on top of your application.

This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.

LoaderConfig
LoaderEvents
LoadMask

A modal, floating Component which may be shown above a specified Component while loading data. When shown, the configured owning Component will be covered with a modality mask, and the LoadMask's msg will be displayed centered, accompanied by a spinner image.

If the store config option is specified, the masking will be automatically shown and then hidden synchronized with the Store's loading process.

Because this is a floating Component, its z-index will be managed by the global ZIndexManager object, and upon show, it will place itsef at the top of the hierarchy.

Example usage:

  
// Basic mask:
            var myMask = new Ext.LoadMask(myPanel, {msg:"Please wait..."});
            myMask.show();
            
LoadMaskConfig
LoadMaskEvents
MessageBox

Singleton instance of Ext.window.MessageBox.

MessageBoxConfig
MessageBoxEvents
ModelManager

The ModelManager keeps track of all Ext.data.Model types defined in your application.

Creating Model Instances

Model instances can be created by using the Ext.create method. Ext.create replaces the deprecated Ext.ModelManager.create method. It is also possible to create a model instance this by using the Model type directly. The following 3 snippets are equivalent:

  
    Ext.define('User', {
            extend: 'Ext.data.Model',
            fields: ['first', 'last']
            });
            // method 1, create using Ext.create (recommended)
            Ext.create('User', {
            first: 'Ed',
            last: 'Spencer'
            });
            // method 2, create through the manager (deprecated)
            Ext.ModelManager.create({
            first: 'Ed',
            last: 'Spencer'
            }, 'User');
            // method 3, create on the type directly
            new User({
            first: 'Ed',
            last: 'Spencer'
            });
            

Accessing Model Types

A reference to a Model type can be obtained by using the getModel function. Since models types are normal classes, you can access the type directly. The following snippets are equivalent:

  
    Ext.define('User', {
            extend: 'Ext.data.Model',
            fields: ['first', 'last']
            });
            // method 1, access model type through the manager
            var UserType = Ext.ModelManager.getModel('User');
            // method 2, reference the type directly
            var UserType = User;
            
ModelManagerConfig
ModelManagerEvents
Number

A collection of useful static methods to deal with numbers

NumberConfig
NumberEvents
Object

A collection of useful static methods to deal with objects.

ObjectConfig
ObjectEvents
PluginManager

Provides a registry of available Plugin classes indexed by a mnemonic code known as the Plugin's ptype.

A plugin may be specified simply as a config object as long as the correct ptype is specified:

  
{
            ptype: 'gridviewdragdrop',
            dragText: 'Drag and drop to reorganize'
            }
            

Or just use the ptype on its own:

  
'gridviewdragdrop'
            

Alternatively you can instantiate the plugin with Ext.create:

  
    Ext.create('Ext.grid.plugin.DragDrop', {
            dragText: 'Drag and drop to reorganize'
            })
            
PluginManagerConfig
PluginManagerEvents
ProgressBar

An updateable progress bar component. The progress bar supports two different modes: manual and automatic.

In manual mode, you are responsible for showing, updating (via updateProgress) and clearing the progress bar as needed from your own code. This method is most appropriate when you want to show progress throughout an operation that has predictable points of interest at which you can update the control.

In automatic mode, you simply call wait and let the progress bar run indefinitely, only clearing it once the operation is complete. You can optionally have the progress bar wait for a specific amount of time and then clear itself. Automatic mode is most appropriate for timed operations or asynchronous operations in which you have no need for indicating intermediate progress.

  
var p = Ext.create('Ext.ProgressBar', {
            renderTo: Ext.getBody(),
            width: 300
            });
            // Wait for 5 seconds, then update the status el (progress bar will auto-reset)
            p.wait({
            interval: 500, //bar will move fast!
            duration: 50000,
            increment: 15,
            text: 'Updating...',
            scope: this,
            fn: function(){
            p.updateText('Done!');
            }
            });
            
ProgressBarConfig
ProgressBarEvents
Shadow

Simple class that can provide a shadow effect for any element. Note that the element MUST be absolutely positioned, and the shadow does not provide any shimming. This should be used only in simple cases - for more advanced functionality that can also provide the same shadow effect, see the Ext.Layer class.

ShadowConfig
ShadowEvents
ShadowPool

NOTE This is a private utility class for internal use by the framework. Don't rely on its existence.

Private utility class that manages the internal Shadow cache.

ShadowPoolConfig
ShadowPoolEvents
String

A collection of useful static methods to deal with strings

StringConfig
StringEvents
supports

Determines information about features are supported in the current environment

supportsConfig
supportsEvents
TaskManager

A static Ext.util.TaskRunner instance that can be used to start and stop arbitrary tasks. See Ext.util.TaskRunner for supported methods and task config properties.

// Start a simple clock task that updates a div once per second var task = {

  
run: function(){
          Ext.fly('clock').update(new Date().format('g:i:s A'));
          },
          interval: 1000 //1 second
            

}

Ext.TaskManager.start(task);

See the start method for details about how to configure a task object.

TaskManagerConfig
TaskManagerEvents
Template

Represents an HTML fragment template. Templates may be precompiled for greater performance.

An instance of this class may be created by passing to the constructor either a single argument, or multiple arguments:

Single argument: String/Array

The single argument may be either a String or an Array:

  • String:

          
    var t = new Ext.Template("<div>Hello {0}.</div>");
                t.append('some-element', ['foo']);
                
  • Array:

    An Array will be combined with join('').

          
    var t = new Ext.Template([
                '<div name="{id}">',
                '<span class="{cls}">{name:trim} {value:ellipsis(10)}</span>',
                '</div>',
                ]);
                t.compile();
                t.append('some-element', {id: 'myid', cls: 'myclass', name: 'foo', value: 'bar'});
                

Multiple arguments: String, Object, Array, ...

Multiple arguments will be combined with join('').

  
var t = new Ext.Template(
            '<div name="{id}">',
            '<span class="{cls}">{name} {value}</span>',
            '</div>',
            // a configuration object:
            {
            compiled: true,      // compile immediately
            }
            );
            

Notes

  • For a list of available format functions, see Ext.util.Format.
  • disableFormats reduces apply time when no formatting is required.
TemplateConfig
TemplateEvents
Version

A utility class that wrap around a string version number and provide convenient method to perform comparison. See also: compare. Example:

  
var version = new Ext.Version('1.0.2beta');
            console.log("Version is " + version); // Version is 1.0.2beta
            console.log(version.getMajor()); // 1
            console.log(version.getMinor()); // 0
            console.log(version.getPatch()); // 2
            console.log(version.getBuild()); // 0
            console.log(version.getRelease()); // beta
            console.log(version.isGreaterThan('1.0.1')); // True
            console.log(version.isGreaterThan('1.0.2alpha')); // True
            console.log(version.isGreaterThan('1.0.2RC')); // False
            console.log(version.isGreaterThan('1.0.2')); // False
            console.log(version.isLessThan('1.0.2')); // True
            console.log(version.match(1.0)); // True
            console.log(version.match('1.0.2')); // True
            
VersionConfig
VersionEvents
WindowManager

The default global floating Component group that is available automatically.

This manages instances of floating Components which were rendered programatically without being added to a Container, and for floating Components which were added into non-floating Containers.

Floating Containers create their own instance of ZIndexManager, and floating Components added at any depth below there are managed by that ZIndexManager.

WindowManagerConfig
WindowManagerEvents
XTemplate

A template class that supports advanced functionality like:

  • Autofilling arrays using templates and sub-templates
  • Conditional processing with basic comparison operators
  • Basic math function support
  • Execute arbitrary inline code with special built-in template variables
  • Custom member functions
  • Many special tags and built-in operators that aren't defined as part of the API, but are supported in the templates that can be created

XTemplate provides the templating mechanism built into Ext.view.View.

The Ext.Template describes the acceptable parameters to pass to the constructor. The following examples demonstrate all of the supported features.

Sample Data

This is the data object used for reference in each code example:

  
var data = {
            name: 'Don Griffin',
            title: 'Senior Technomage',
            company: 'Sencha Inc.',
            drinks: ['Coffee', 'Water', 'More Coffee'],
            kids: [
            { name: 'Aubrey',  age: 17 },
            { name: 'Joshua',  age: 13 },
            { name: 'Cale',    age: 10 },
            { name: 'Nikol',   age: 5 },
            { name: 'Solomon', age: 0 }
            ]
            };
            

Auto filling of arrays

The tpl tag and the for operator are used to process the provided data object:

  • If the value specified in for is an array, it will auto-fill, repeating the template block inside the tpl tag for each item in the array.
  • If for="." is specified, the data object provided is examined.
  • While processing an array, the special variable {#} will provide the current array index + 1 (starts at 1, not 0).

Examples:

  
<tpl for=".">...</tpl>       // loop through array at root node
            <tpl for="foo">...</tpl>     // loop through array at foo node
            <tpl for="foo.bar">...</tpl> // loop through array at foo.bar node
            

Using the sample data above:

  
var tpl = new Ext.XTemplate(
            '<p>Kids: ',
            '<tpl for=".">',       // process the data.kids node
            '<p>{#}. {name}</p>',  // use current array index to autonumber
            '</tpl></p>'
            );
            tpl.overwrite(panel.body, data.kids); // pass the kids property of the data object
            

An example illustrating how the for property can be leveraged to access specified members of the provided data object to populate the template:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Title: {title}</p>',
            '<p>Company: {company}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',     // interrogate the kids property within the data
            '<p>{name}</p>',
            '</tpl></p>'
            );
            tpl.overwrite(panel.body, data);  // pass the root node of the data object
            

Flat arrays that contain values (and not objects) can be auto-rendered using the special {.} variable inside a loop. This variable will represent the value of the array at the current index:

  
var tpl = new Ext.XTemplate(
            '<p>{name}\'s favorite beverages:</p>',
            '<tpl for="drinks">',
            '<div> - {.}</div>',
            '</tpl>'
            );
            tpl.overwrite(panel.body, data);
            

When processing a sub-template, for example while looping through a child array, you can access the parent object's members via the parent object:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<tpl if="age &gt; 1">',
            '<p>{name}</p>',
            '<p>Dad: {parent.name}</p>',
            '</tpl>',
            '</tpl></p>'
            );
            tpl.overwrite(panel.body, data);
            

Conditional processing with basic comparison operators

The tpl tag and the if operator are used to provide conditional checks for deciding whether or not to render specific parts of the template.

Using the sample data above:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<tpl if="age &gt; 1">',
            '<p>{name}</p>',
            '</tpl>',
            '</tpl></p>'
            );
            tpl.overwrite(panel.body, data);
            

More advanced conditionals are also supported:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<p>{name} is a ',
            '<tpl if="age &gt;= 13">',
            '<p>teenager</p>',
            '<tpl elseif="age &gt;= 2">',
            '<p>kid</p>',
            '<tpl else>',
            '<p>baby</p>',
            '</tpl>',
            '</tpl></p>'
            );
            var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<p>{name} is a ',
            '<tpl switch="name">',
            '<tpl case="Aubrey" case="Nikol">',
            '<p>girl</p>',
            '<tpl default>',
            '<p>boy</p>',
            '</tpl>',
            '</tpl></p>'
            );
            

A break is implied between each case and default, however, multiple cases can be listed in a single <tpl> tag.

Using double quotes

Examples:

  
var tpl = new Ext.XTemplate(
            "<tpl if='age &gt; 1 && age &lt; 10'>Child</tpl>",
            "<tpl if='age &gt;= 10 && age &lt; 18'>Teenager</tpl>",
            "<tpl if='this.isGirl(name)'>...</tpl>",
            '<tpl if="id == \'download\'">...</tpl>',
            "<tpl if='needsIcon'><img src='{icon}' class='{iconCls}'/></tpl>",
            "<tpl if='name == \"Don\"'>Hello</tpl>"
            );
            

Basic math support

The following basic math operators may be applied directly on numeric data values:

  
+ - * /
            

For example:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<tpl if="age &gt; 1">',  // <-- Note that the > is encoded
            '<p>{#}: {name}</p>',  // <-- Auto-number each item
            '<p>In 5 Years: {age+5}</p>',  // <-- Basic math
            '<p>Dad: {parent.name}</p>',
            '</tpl>',
            '</tpl></p>'
            );
            tpl.overwrite(panel.body, data);
            

Execute arbitrary inline code with special built-in template variables

Anything between {[ ... ]} is considered code to be executed in the scope of the template. The expression is evaluated and the result is included in the generated result. There are some special variables available in that code:

  • out: The output array into which the template is being appended (using push to later join).
  • values: The values in the current scope. If you are using scope changing sub-templates, you can change what values is.
  • parent: The scope (values) of the ancestor template.
  • xindex: If you are in a looping template, the index of the loop you are in (1-based).
  • xcount: If you are in a looping template, the total length of the array you are looping.

This example demonstrates basic row striping using an inline code block and the xindex variable:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<div class="{[xindex % 2 === 0 ? "even" : "odd"]}">',
            '{name}',
            '</div>',
            '</tpl></p>'
            );
            

Any code contained in "verbatim" blocks (using "{% ... %}") will be inserted directly in the generated code for the template. These blocks are not included in the output. This can be used for simple things like break/continue in a loop, or control structures or method calls (when they don't produce output). The this references the template instance.

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Company: {[values.company.toUpperCase() + ", " + values.title]}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '{% if (xindex % 2 === 0) continue; %}',
            '{name}',
            '{% if (xindex > 100) break; %}',
            '</div>',
            '</tpl></p>'
            );
            

Template member functions

One or more member functions can be specified in a configuration object passed into the XTemplate constructor for more complex processing:

  
var tpl = new Ext.XTemplate(
            '<p>Name: {name}</p>',
            '<p>Kids: ',
            '<tpl for="kids">',
            '<tpl if="this.isGirl(name)">',
            '<p>Girl: {name} - {age}</p>',
            '<tpl else>',
            '<p>Boy: {name} - {age}</p>',
            '</tpl>',
            '<tpl if="this.isBaby(age)">',
            '<p>{name} is a baby!</p>',
            '</tpl>',
            '</tpl></p>',
            {
            // XTemplate configuration:
            disableFormats: true,
            // member functions:
            isGirl: function(name){
            return name == 'Aubrey' || name == 'Nikol';
            },
            isBaby: function(age){
            return age < 1;
            }
            }
            );
            tpl.overwrite(panel.body, data);
            
XTemplateCompiler

NOTE This is a private utility class for internal use by the framework. Don't rely on its existence.

This class compiles the XTemplate syntax into a function object. The function is used like so:

  
function (out, values, parent, xindex, xcount) {
           // out is the output array to store results
           // values, parent, xindex and xcount have their historical meaning
           }
            
XTemplateCompilerConfig
XTemplateCompilerEvents
XTemplateConfig
XTemplateEvents
XTemplateParser

NOTE This is a private utility class for internal use by the framework. Don't rely on its existence.

This class parses the XTemplate syntax and calls abstract methods to process the parts.

XTemplateParserConfig
XTemplateParserEvents
ZIndexManager

A class that manages a group of Ext.Component.floating Components and provides z-order management, and Component activation behavior, including masking below the active (topmost) Component.

Floating Components which are rendered directly into the document (such as Windows) which are shown are managed by a global instance.

Floating Components which are descendants of floatingContainers (for example a BoundList within an Window, or a Menu), are managed by a ZIndexManager owned by that floating Container. Therefore ComboBox dropdowns within Windows will have managed z-indices guaranteed to be correct, relative to the Window.

ZIndexManagerConfig
ZIndexManagerEvents
© Copyright 2005-2011 SharpKit. All rights reserved.