Writing an Ext JS Plugin

In this article I will show you how to write an Ext JS plugin that displays how many characters you can type on a textarea before the a maximum number of characters is reached. 

extjs-plugin-1

Our plugin will subscribe to the keyup event of the textarea, and will use the textarea’s maxLength property and getValue() function to calculate how many characters can still be typed before the maxLength value is reached. The current and maximun number of characters will be displayed using a div element that will be rendered below the textarea’s html input field.

The basic code template of an Ext JS plugin

An Ext JS plugin gains access to its host component via a its init() function, that takes a reference to the component, and is called after the component is initialized but before it is rendered. 

Any code template for a plugin in Ext JS must include the init() function.  Our plugin will use the following template:

Ext.ns('Plugins');

Plugins.CharsLeftReminder = (function() {

    return {

        init: function(field) {

        }
    };
});

Implementing the Ext JS plugin

In the init() function, we will first make sure the plugin’s host is a textarea:

init: function(field) { 

    var thisXType = field.getXType(); 

    if (false == (field instanceof Ext.form.TextArea)) return; // We only want to modify textarea fields. 

}

We also define the function that will return the characters left, as well as the handler for the keyup event: 

init: function(field) {

    ...

    var maxChars = field.maxLength;
    var charsLeft;
    var suffix = ' of ' + maxChars + ' characters left';
    var instanceId = field.id + '-charsLeft';

    var getCharsLeft = function(field) {
        var charsLeft = maxChars - field.getValue().length;
        return charsLeft;
    };

    var keyupHandler = function(f, evt) {
        charsLeft = getCharsLeft(f);
        Ext.getDom(instanceId).innerHTML = charsLeft + suffix;
    };
    
}

Finally, we use the createSequence() function to define our own onRender() and onDestroy() methods, to be called after the textarea’s onRender() and onDestroy():

init: function(field) {

    ...

    Ext.apply(field, {
        enableKeyEvents: true,
        onRender: field.onRender.createSequence(function(ct, position) {
            if (Ext.getDom(instanceId)) return;
		charsLeft = getCharsLeft(field);
            var reminder = {
                tag: 'div',
                id: instanceId,
                html: charsLeft + suffix,
                style: 'padding:1px 1px 5px 1px;'
            }
            Ext.DomHelper.insertAfter(this.el, reminder);
            field.on('keyup', keyupHandler);
        }),
        onDestroy: field.onDestroy.createSequence(function() {
            var el = Ext.getDom(instanceId);
            if (el) {
                Ext.removeNode(el);
            }
        })
    });

}

Besides connecting the keyupHandler function to the keyup event, our onRender() implementation defines a div element that will display the “[N] of [maxLength] characters left” message.  We use DomHelper.inserAfter() to add this div to the DOM immediately after the textarea’s html input field.

Notice that  we use enableKeyEvents to enable the broadcast of key events from the textarea’s html input field.

To be on the safe side, we clean after ourselves by using onDestroy() to remove our plugin’s DOM node from the DOM.

This completes the plugin implementation.  Now we can use it, as in the following example:

Plugins.updateForm = new Ext.FormPanel({
    id: 'updateForm',
    frame: true,
    renderTo: Ext.getBody(),
    title: 'What\'s happening?',
    bodyStyle: 'padding:5px',
    width: 550,
    layout: 'form',
    items: [
        {
            xtype: 'textarea',
            hideLabel: true,
            name: 'comments',
            anchor: '100%',
            height: 100,
            maxLength: 140,
            plugins: [new Plugins.CharsLeftReminder()]
        }
    ],
    buttons: [{
        text: 'Send'
    }, {
        text: 'Cancel',
        handler: function() {
            Ext.getCmp('updateForm').destroy();
        }
    }]
});

Downloads

Grab the code for the sample from my downloads page.

Want to learn more?

Ext-JS-Cookbook My Ext JS 3.0 Cookbook has more than a hundred step-by-step recipes that you can use to build your Ext JS applications.  Download a sample chapter and see for yourself.

E-mail   Permalink    Comments(1)   Trackback

Tags: , ,

What Is An ExtJS Plugin?

Here are some facts that will help you understand Ext JS plugins.

  • An ExtJS plugin is a class that defines and encapsulates behavior to be added to one or more ExtJS components.
  • Plugins are attached to their target component(s) via the plugins configuration option
  • Instead of exposing services that the target component can use, a plugin gains access to the component via a required function, init(), that takes a reference to the component
  • A plugin's init() function is called at a specific point of its target component's lifecycle: after the component is initialized and before it is rendered
  • A plugin can be lazy-instantiated if its target is lazy-instantiated

Can you spot the differences and similarities with other ways of modifying component behavior in ExtJS, for example, subclassing and configuration options?

E-mail   Permalink    Comments(0)   Trackback

Tags: ,