Factory Functions in Ext Extensions (Abstract Classes)

7. August 2010 – 15:37

I have recently run across one of the the Jay Garcia’s excellent screencasts Abstract classes with Ext JS. (Thank you Jay for your effort of educating Ext JS community.)

I’ve been consulting in a company at that time – developers of the client, after seeing the screencast, immediately asked me: “So what should we use? The ‘xtype’ style or Abstract classes?”

The curt answer would be: “Use whatever you prefer.” or “Use both”.

However, decisions based on mere “preference” or on “I use it because it is available” are often not fully rational and can lead to troubles as the application grows. Thus, let’s take a deeper look to see if there are any pitfalls and to find how can we get most of both methods.

Note: Before you continue, read “Writing a big application in Ext”, watch the Jay’s screencast and understand both, otherwise, the following text won’t make any sense to you.

Abstract ExtJS Class

Abstract classes are not to be used directly but they serve more like templates that specify methods and properties to be implemented in classes derived from them. They are very useful in object oriented programming because they force developers to implement all mandatory methods with same signature (signature = arguments the method or function accepts) and return values so there is a greater chance to develop a bug free code.

However, in ExtJS (and JavaScript that is scripting language where source is not compiled but directly interpreted), there is no mechanism to warn developer “you haven’t implemented method XY” or “your implementation has wrong signature” so we need to take care ourselves.

Nevertheless, the idea of abstract classes is useful also in JavaScript/ExtJS environment because:

  1. logic and configuration common to all expected descendants can be put in the abstract base class that eliminates the code duplication, speeds up development and debugging, and increases future code maintainability greatly
  2. abstract classes tell us which methods to implement
  3. it increases the human readability of the code (Remember, we always try to write the code to be readable and understandable by us and others in the future.)

The Basic Idea

The basic idea Jay presents in his great screencast is to extend an Ext Component, FormPanel for example, and add stub methods to it:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     submitUrl:null
    ,initComponent:function() {
        Ext.apply(this, {
             items:this.buildItems()
            ,buttons:this.buildButtons()
        });
 
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildItems:function() {
        return [];
    } // eo function buildItems
 
    ,buildButtons:function() {
        return [];
    } // eo function buildButtons
 
}); // eo extend

The empty “buildXxx” methods will be implemented in the abstract class extension.

Tweaking the Abstract Class example

While perfect for the educational purposes, we need to tweak this code if want to use it in the production quality application. I shall walk you through recommended improvements.

initialConfig

Ext.Component takes the config object passed to its constructor and saves it in the object variable initialConfig when it instantiates. Although items and buttons in combination with the FormPanel in the above example do not rely on it, so the example runs as expected, initialConfig is used on the Ext.Component level so it may be used by any of Component descendants.

Let’s take care of it and modify initComponent as follows:

    ,initComponent:function() {
        // create config object
        var config = {};
 
        // build config properties
        Ext.apply(config, {
             items:this.buildItems()
            ,buttons:this.buildButtons()
        });
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent

Return Values

Abstract methods in the example return empty arrays. That is no problem for items or buttons but if we want to have also buildTbar or buildBbar factory functions that return empty arrays [] then top and bottom toolbars are always created, but empty, if methods are not implemented in derived classes. (Empty toolbars are quite ugly when rendered.)

Therefore, always return undefined from the abstract methods. For now, the class could look like this:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     submitUrl:null
    ,initComponent:function() {
        // create config object
        var config = {};
 
        // build config properties
        Ext.apply(config, {
             items:this.buildItems()
            ,buttons:this.buildButtons()
            ,tbar:this.buildTbar()
            ,bbar:this.buildBbar()
        });
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildItems:function() {
        return undefined;
    } // eo function buildItems
 
    ,buildButtons:function() {
        return undefined;
    } // eo function buildButtons
 
    ,buildTbar:function() {
        return undefined;
    } // eo function buildTbar
 
    ,buildBbar:function() {
        return undefined;
    } // eo function buildBbar

Passing config to Abstract Factory Methods

If we pass config object to abstract methods then we can apply the created items, buttons, toolbar items directly to it. That has no great benefit in itself, however, if we create a sequence or interceptor of these methods we can use the config object directly.

So now we have:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     submitUrl:null
    ,initComponent:function() {
        // create config object
        var config = {};
 
        // build config properties
        this.buildItems(config);
        this.buildButtons(config);
        this.buildTbar(config);
        this.buildBbar(config);
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildItems:function(config) {
        config.items = undefined;
    } // eo function buildItems
 
    ,buildButtons:function(config) {
        config.buttons = undefined;
    } // eo function buildButtons
 
    ,buildTbar:function(config) {
        config.tbar = undefined;
    } // eo function buildTbar
 
    ,buildBbar:function(config) {
        config.bbar = undefined;
    } // eo function buildBbar
 
}); // eo extend

The Final Touch

If you look in the initComponent now you see that we call a series of “build” functions in it. Let’s move it into another factory method:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     submitUrl:null
    ,initComponent:function() {
        // create config object
        var config = {};
 
        // build config
        this.buildConfig(config);
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildConfig:function(config) {
        this.buildItems(config);
        this.buildButtons(config);
        this.buildTbar(config);
        this.buildBbar(config);
    } // eo function buildConfig
 
    ,buildItems:function(config) {
        config.items = undefined;
    } // eo function buildItems
 
    ,buildButtons:function(config) {
        config.buttons = undefined;
    } // eo function buildButtons
 
    ,buildTbar:function(config) {
        config.tbar = undefined;
    } // eo function buildTbar
 
    ,buildBbar:function(config) {
        config.bbar = undefined;
    } // eo function buildBbar
 
}); // eo extend

The above gives you the flexibility of implementing or overriding of the whole buildConfig function or individual items, buttons, bars functions. It also takes care of initialConfig problem.

It’s a kind of a “pattern” and I will publish it in my “file patterns” series on this blog with more code comments.

Example

If we build upon Jay’s example, using the pattern above, we get:

AbstractFormPanel.js:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     defaultType:'textfield'
    ,frame:true
    ,width:300
    ,height:200
    ,labelWidth:75
    ,submitUrl:null
    ,submitT:'Submit'
    ,cancelT:'Cancel'
    ,initComponent:function() {
 
        // create config object
        var config = {
            defaults:{anchor:'-10'}
        };
 
        // build config
        this.buildConfig(config);
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildConfig:function(config) {
        this.buildItems(config);
        this.buildButtons(config);
        this.buildTbar(config);
        this.buildBbar(config);
    } // eo function buildConfig
 
    ,buildItems:function(config) {
        config.items = undefined;
    } // eo function buildItems
 
    ,buildButtons:function(config) {
        config.buttons = [{
             text:this.submitT
            ,scope:this
            ,handler:this.onSubmit
            ,iconCls:'icon-disk'
        },{
             text:this.cancelT
            ,scope:this
            ,handler:this.onCancel
            ,iconCls:'icon-undo'
        }];
    } // eo function buildButtons
 
    ,buildTbar:function(config) {
        config.tbar = undefined;
    } // eo function buildTbar
 
    ,buildBbar:function(config) {
        config.bbar = undefined;
    } // eo function buildBbar
 
    ,onSubmit:function() {
        Ext.MessageBox.alert('Submit', this.submitUrl);
    } // eo function onSubmit
 
    ,onCancel:function() {
        this.el.mask('This form is canceled');
    } // eo function onCancel
 
}); // eo extend

Mention please that I moved hard-wired button texts to class properties. The reason is that this way we can easily localize (translate) these texts to another languages. I didn’t take care of messages of handlers though. You will do in your localizable applications, won’t you?

AddressFormPanel.js:

Ext.ns('MyApp');
 
MyApp.AddressFormPanel = Ext.extend(MyApp.AbstractFormPanel, {
     title:'Edit address data'
    ,submitUrl:'addressAction.asp'
    ,buildItems:function(config) {
        config.items = [{
             name:'address1'
            ,fieldLabel:'Address 1'
        },{
             name:'address2'
            ,fieldLabel:'Address 2'
        },{
             name:'city'
            ,fieldLabel:'city'
        },{
             xtype:'combo'
            ,name:'state'
            ,fieldLabel:'State'
            ,store:['MD', 'VA', 'DC']
        },{
             xtype:'numberfield'
            ,name:'zip'
            ,fieldLabel:'Zip Code'
        }];
    } // eo function buildItems
 
});
 
// eof

NameFormPanel.js:

Ext.ns('MyApp');
 
MyApp.NameFormPanel = Ext.extend(MyApp.AbstractFormPanel, {
     title:'Edit name data'
    ,submitUrl:'nameAction.asp'
    ,okT:'OK'
 
    ,buildItems:function(config) {
        config.items = [{
             name:'firstName'
            ,fieldLabel:'First Name'
        },{
             name:'lastName'
            ,fieldLabel:'Last Name'
        },{
             name:'middleName'
            ,fieldLabel:'Middle Name'
        },{
             xtype:'datefield'
            ,name:'dob'
            ,fieldLabel:'DOB'
        }];
    } // eo function buildItems
 
    //Extension
    ,buildButtons:function(config) {
 
        // let parent build buttons first
        MyApp.NameFormPanel.superclass.buildButtons.apply(this, arguments);
 
        // tweak the submit button
        config.buttons[0].text = this.okT;
        config.buttons[0].handler = this.onOkBtn;
 
    } // eo function buildButtons
 
    //Override
    ,onOkBtn:function() {
        console.info('OK btn pressed');
    } // eo function onOkBtn
 
}); // eo extend
 
// eof

With this setup, we can even create instance of AbstractForm panel directly passing some/all build functions inline:

var nameForm = new MyApp.AbstractFormPanel({
     title:'Name Form Panel configured inline'
    ,width:300
    ,height:200
    ,renderTo:Ext.getBody()
    ,buildItems:function(config) {
        config.items = [{
             name:'firstName'
            ,fieldLabel:'First Name'
        },{
             name:'lastName'
            ,fieldLabel:'Last Name'
        },{
             name:'middleName'
            ,fieldLabel:'Middle Name'
        },{
             xtype:'datefield'
            ,name:'dob'
            ,fieldLabel:'DOB'
        }];
    } // eo function buildItems
});

Note: Although the above works, it violates the rule of not instantiating an abstract class directly. It’s up to you if you will do it or not.

Combining with “xtypes”

Now, do not succumb to the temptation of “putting everything” in factory functions. Abstract classes are just a programming style, not an universal solvent.

Imagine, you have your own carefully crafted Submit and Cancel buttons so if you would “put everything” in the factory functions you would need to copy buttons configurations many times because also toolbars, grids, data views, etc can contain them.

Create extensions (xtypes) for those buttons instead. The following illustrates the approach:

SubmitButton.js

Ext.ns('MyApp');
 
MyApp.SubmitButton = Ext.extend(Ext.Button, {
     text:'Submit'
    ,iconCls:'icon-disk'
    ,initComponent:function() {
        MyApp.SubmitButton.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
}); // eo extend
 
Ext.reg('submitbutton', MyApp.SubmitButton);
 
// eof

CancelButton.js:

Ext.ns('MyApp');
 
MyApp.CancelButton = Ext.extend(Ext.Button, {
     text:'Cancel'
    ,iconCls:'icon-undo'
    ,initComponent:function() {
        MyApp.CancelButton.superclass.initComponent.apply(this, arguments);
    } // eo function initComponent
}); // eo extend
 
Ext.reg('cancelbutton', MyApp.CancelButton);
 
// eof

and AbstractFormPanel.js:

Ext.ns('MyApp');
 
MyApp.AbstractFormPanel = Ext.extend(Ext.form.FormPanel, {
     defaultType:'textfield'
    ,frame:true
    ,width:300
    ,height:200
    ,labelWidth:75
    ,submitUrl:null
    ,initComponent:function() {
 
        // create config object
        var config = {
            defaults:{anchor:'-10'}
        };
 
        // build config
        this.buildConfig(config);
 
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
 
        // call parent
        MyApp.AbstractFormPanel.superclass.initComponent.call(this);
 
    } // eo function initComponent
 
    ,buildConfig:function(config) {
        this.buildItems(config);
        this.buildButtons(config);
        this.buildTbar(config);
        this.buildBbar(config);
    } // eo function buildConfig
 
    ,buildItems:function(config) {
        config.items = undefined;
    } // eo function buildItems
 
    ,buildButtons:function(config) {
        config.buttons = [{
             xtype:'submitbutton'
            ,scope:this
            ,handler:this.onSubmit
        },{
             xtype:'cancelbutton'
            ,scope:this
            ,handler:this.onCancel
        }];
    } // eo function buildButtons
 
    ,buildTbar:function(config) {
        config.tbar = undefined;
    } // eo function buildTbar
 
    ,buildBbar:function(config) {
        config.bbar = undefined;
    } // eo function buildBbar
 
    ,onSubmit:function() {
        Ext.MessageBox.alert('Submit', this.submitUrl);
    } // eo function onSubmit
 
    ,onCancel:function() {
        this.el.mask('This form is canceled');
    } // eo function onCancel
 
}); // eo extend
 
// eof

Note: The above buttons are far too simple to be extended in the real world but you get the point, right?

Conclusion

Abstract classes, as Jay Garcia defines and presents them, are a very useful ExtJS programming technique and if you use them in the information provided in this post your code will be clean, flexible and maintainable. That is what all we developers want.

Happy coding!

Further reading:

  1. Writing a Big Application in Ext
  2. Abstract classes with Ext JS

New Example – Grid in Card Layout

13. October 2009 – 14:49

Hi all,

I’ve just uploaded new example of Grid in Card Layout

Enjoy!

How to Convert DVD to iPhone Video with Subtitles and Chapters on Linux

4. October 2009 – 23:02

iPhone can play video that contains multiple streams and chapters:

  • video
  • multiple audio streams (languages)
  • multiple subtitles (languages)
  • chapters for easy navigation

After some googling and many trials and errors I found a multiplatform software that can create videos with all the above features. The software is HandBrake. HandBrake for (openSUSE) Linux can be downloaded from Packman.

Let’s convert our DVD to the iPhone video. For that insert an original DVD in the drive, start HandBrake and select source.

dvd2ipod-01

Select iPhone & iPod Touch preset and type the file name and the destination directory.

dvd2ipod-02

There is not too much to set on Video tab, however, you can play with quality if you want.

dvd2ipod-03

In Audio tab, add as many audio tracks as you want:

dvd2ipod-04

If you want to “burn” subtitles into video, just select one from the original DVD and you’re done. More difficult is if you want Closed Captioning subtitles (that can be turned off on iPhone). For that you need external files with subtitles in srt format. You can download them from opensubtitles.org. The problem can be that the downloaded subtitles may not be in sync with you video. I haven’t found a better way only to encode the DVD and, if subtitles are out of sync, use Subtitle Composer to adjust the timing(s) and re-encode.

dvd2ipod-05

Default settings in H.264 tab do not need any change.

dvd2ipod-06

Rename chapters if you want. Names are sometimes on DVD covers, sometimes not.

dvd2ipod-07

Start encoding, wait an hour or so and then download the resulting video to your iPhone with iTunes.

How to extract subtitles from DVD

2. October 2009 – 11:11
mencoder dvd://1 -oac copy -ovc copy -o /dev/null -vobsubout output -sid 1

Then use avidemux2_qt4

Keeping modified records of EditorGridPanel while paging

28. September 2009 – 10:59

If you modify records of an editable grid with paging and if you then page-out, your changes are lost. Well, they are not lost in fact unless you have set pruneModifiedRecords:true on the strore. The modifications are still available so we just need to apply them. Here is the code fragment that does it:

var grid = new Ext.grid.EditorGridPanel({
    store:new Ext.data.Store({
         listeners:{
            load:{scope:this, fn:function(store) {
 
                // loop through modified records
                var modified = store.getModifiedRecords();
                for(var i = 0; i < modified.length; i++) {
 
                    // see if we have a record with same id 
                    // and apply changes if yes
                    var r = store.getById(modified[i].id);
                    if(r) {
                        var changes = modified[i].getChanges();
                        for(p in changes) {
                            if(changes.hasOwnProperty(p)) {
                                r.set(p, changes[p]);
                            }
                        } // eo changes loop
                    }
                } // eo modified loop
            }} // eo load listener
        } // eo listeners
 
        // rest of store configuration
 
    })
 
    // rest of grid configuration
 
}) // eo grid

pruneModifiedRecords must be false (the default) for this to work.

New Example – Ext.ux.MsgBus Demo

20. September 2009 – 23:48

Hi there,

I’ve just uploaded demo of Ext.ux.MsgBus Plugin at http://examples.extjs.eu/?ex=msgbus.

Enjoy!

Ext.ux.MsgBus Plugin

20. September 2009 – 14:45

Recently I’ve been looking for a better way of inter-component communication in Ext so I’ve read a couple of posts with Message Bus implementations, I’ve skimmed over OpenAjax Hub page but I haven’t found anything suitable for my needs.

The first approach was Simple Message Bus Example but that is more concept proof than a really usable way in production environment.

I like the concept of message subjects (topics) as dot separated sequence of tokens with the ability to subscribe to messages with specific subjects and with wildcard support.

For example, if a component would subscribe to the subject eu.extjs.desktop.** it would receive message with subject eu.extjs.desktop.wallpaper.set but it wouldn’t receive message eu.extjs.taskbar.hide.

So this plugin was born.

Ext.ux.MsgBus fits in any component that is descendant of Ext.util.Observable and it does not need any other changes/overrides. You would stick it only into the components that must participate in bus messaging. It adds subscribe and publish methods to the component.

Usage example:

var p = new Ext.Panel({
     plugins:['msgbus']
    ,onWallpaper:function(subject, message) {
        // do something
    }
    // the rest of config
});
p.subscribe('eu.extjs.desktop.wallpaper.**', {fn:p.onWallpaper, single:true});

The above would call p.onWallpaper callback once upon the receipt of a “wallpaper” message.

Other example:

p.publish('eu.extjs.this.panel.move', {oldx:100, oldy:200, x:300, y:400});

I haven’t tested it fully yet so take it more as an initial idea than as a bullet-proof, worldwide-tested code. Also, I didn’t try in any means to implement OpenAjax standards and use this plugin for an inter library communication. Consider it as a one possibility of intra-Ext, inter-component communication.

Any comments and/or bug reports are welcome.

// vim: sw=4:ts=4:nu:nospell:fdc=4
/**
 * Message Bus Plugin
 *
 * @author    Ing. Jozef Sakáloš
 * @copyright (c) 2009, by Ing. Jozef Sakáloš
 * @date      19. September 2009
 * @version   $Id: Ext.ux.MsgBus.js 29 2009-09-23 09:51:55Z jozo $
 *
 * @license Ext.ux.MsgBus.js is licensed under the terms of the Open Source
 * LGPL 3.0 license. Commercial use is permitted to the extent that the 
 * code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 */
 
/*global Ext,window */
 
/**
 * @class Ext.ux.MsgBus
 *
 * Creates new Ext.ux.MsgBus object
 * @constructor
 * @param {Object} config The config object
 */
Ext.ux.MsgBus = function(config) {
    Ext.apply(this, config, {
    });
}; // eo constructor
 
Ext.override(Ext.ux.MsgBus, {
    /**
     * @cfg {String} busName Name of the global Observable instance
     */
     busName:'Ext.ux.Bus'
    /**
     * @private
     */
    ,bus:false
    /**
     * Initializes the plugin and component
     * @private
     */
    ,init:function(cmp) {
        this.cmp = cmp;
        cmp.bus = this.getBus();
        cmp.bus.addEvents('message');
        cmp.subs = {};
        this.applyConfig();
    } // eo function init
    // {{{
    /**
     * Returns or creates the global Observable instance
     * @private
     */
    ,getBus:function() {
        var bus = window;
        var a = this.busName.split('.');
        var last = a.pop();
        Ext.each(a, function(n) {
            if(!Ext.isObject(bus[n])) {
                bus = false;
                return false;
            }
            else {
                bus = bus[n];
            }
        }, this);
        if(false === bus) {
            Ext.ns(this.busName);
            return this.getBus();
        }
        if(!(bus[last] instanceof Ext.util.Observable)) {
            bus[last] = new Ext.util.Observable();
        }
        return bus[last];
    } // eo function getBus
    // }}}
    // {{{
    /**
     * Creates RegExp for message filtering.
     * Override it if you need another logic.
     * @param {String} subject The message subject
     * @return {RegExp} RegExp used for message filtering
     */
    ,getFilterRe:function(subject) {
        var a = subject.split('.');
        var last = a.length - 1;
        a[last] = '**' === a[last] ? '.*' : a[last];
        var re = /^\w+$/;
        Ext.each(a, function(token, i) {
            if(!re.test(token) && '*' !== token && '.*' !== token) {
                throw 'Invalid subject: ' + subject;
            }
            if('*' === token) {
                a[i] = '\\w+';
            }
        });
        return new RegExp('^' + a.join('\\.') + '$');
    } // eo function getFilter
    // }}}
    // {{{
    /**
     * Applies new methods to the component
     * @private
     */
    ,applyConfig:function() {
        Ext.applyIf(this.cmp, {
            /**
             * Subscribes to messages (parent component method)
             * @param {String} subject Dotted notation subject with wildcards.
             * See http://www.openajax.org/member/wiki/OpenAjax_Hub_2.0_Specification_Topic_Names
             * @param {Object} config Same as addListener config object
             * @return {Boolean} success true on success, false on failure (subscription exists)
             */
             subscribe:function(subject, config) {
                 var sub = this.subs[subject];
                if(sub) {
                    return false;
                }
                config = config || {};
                config.filter = this.getFilterRe(subject);
                this.subs[subject] = {config:config, fn:this.filterMessage.createDelegate(this, [config], true)};
                this.bus.on('message', this.subs[subject].fn, config.scope || this, config);
                return true;
            }
 
            /**
             * Unsubscribes from messages (parent component method)
             * @param {String} subject Dotted notation subject with wildcards.
             * @return {Boolean} success true on success, false on failure (nonexistent subscription)
             */
            ,unsubscribe:function(subject) {
                var sub = this.subs[subject];
                if(!sub) {
                    return false;
                }
                this.bus.un('message', sub.fn, sub.scope || this, sub.config);
                delete this.subs[subject];
                sub = null;
                return true;
            } // eo function unsubscribe
 
            /**
             * Publishes the message (parent component method)
             * @param {String} subject Message subject
             * @param {Mixed} message Message body, most likely an object
             */
            ,publish:function(subject, message) {
                this.getFilterRe(subject);
                this.bus.fireEvent('message', subject, message);
            } // eo function publish
 
            /**
             * Returns current subscriptions
             * @return {Object} subscriptions
             */
            ,getSubscriptions:function() {
                return this.subs;
            } // eo function
 
            /**
             * @private
             */
            ,getFilterRe:this.getFilterRe
 
            /**
             * Filters incoming messages
             * @private
             */
            ,filterMessage:function(subject, message, config) {
                if(config.filter.test(subject)) {
                    (config.fn || this.onMessage).call(config.scope || this, subject, message);
                }
            } // eo function filterMessage
 
            /**
             * Default message processing function
             * @param {String} subject The message subject
             * @param {Mixed} message The message body
             */
            ,onMessage:Ext.emptyFn
        });
    } // eo function applyConfig
    // }}}
 
}); // eo override
 
// register ptype
Ext.preg('msgbus', Ext.ux.MsgBus); 
 
// eof

Enjoy!

The accompanying example: Ext.ux.MsgBus

New Example – Simple Message Bus

19. September 2009 – 22:02

Hi all,

I’ve just uploaded very simple, extremely simple, example of how to implement Message Bus in Ext using the global Ext.util.Observable instance.

Enjoy!

Simple Message Bus Example

See also: Ext.ux.MsgBus Plugin

What the hell is mon and mun?

18. September 2009 – 02:31

I’ve run across the following code in some of Ext 3.x examples:

this.mon(toolsUl, 'click', this.onClick, this);

Looks like event handler installation but what it really does anyway?

So I delved into the code and remembered ExtJS Conference and now it is clear to me.

Imagine you create a component and then you need to install an event handler, for example, on its body. Something like:

var handler = function() {
    alert('You clicked my body');
};
var p = new Ext.Panel({
     renderTo:Ext.getBody()
    ,title:'Panel with a listener on the body'
});
p.body.on('click', handler);

Easy enough, we’ve done something like this many times. But, if the panel is ever to be destroyed we need to remove this listener ourselves as Ext knows nothing about it.

Something like:

var p = new Ext.Panel({
     renderTo:Ext.getBody()
    ,title:'Panel with a listener on the body'
    ,beforeDestroy:function() {
        this.body.un('click', handler);
    }
});

If we install our listener as inline function, such as:

p.on('click', function() {alert('You clicked my body')});

then it is impossible to remove this listener selectively, you would need to use

p.body.removeAllListeners();

to remove all body listeners.

Now, if we use mon (m stands for “managed”) this way

p.mon(p.body, 'click', handler);

then the listener is automatically removed by Ext on panel destroy. Nice, isn’t it? Saves a lot of our work and also handles our laziness or forgetfulness about destroying and cleanups of components.

Mind the first argument, that is the element to install the listener to. It can, but not necessarily have to be within the component. Also remember that when you destroy p Ext only removes listener from the element so if the element is outside of p you need to remove it yourself if it is not necessary anymore.

Should you ever need to remove the listener installed by mon you use mun with same arguments. You cannot selectively remove inline listeners.

mon and mun are defined in Component so you can use them from Component down the descendant classes chain.

Warning! mon and mun are not documented (yet?) so there is still (a little) risk that they will change or will be removed.

 

Mastering Ext.Direct, Part 3

17. September 2009 – 14:20

<<< Mastering Ext.Direct, Part 2

Processing responses

As I’ve already said, you cannot use the return value of an API function call as result is not know at the moment of the call return. It is never stressed enough that

Ext.Direct calls are ASYNCHRONOUS.

Therefore, all Ext.Direct created API functions, for example Example.Car.go() take one extra argument in addition to arguments you have specified in server-side class definition. That argument is callback function.

In our example, Example.Car.go() takes one argument, speed per server side method definition, however, it takes two in fact: Example.Car.go(speed, callback)

Let’s call it with a callback to test it. Type in the Firebug console:

Example.Car.go(80, console.info);

console.info is a function that prints its arguments in a human readable form. We use it as the callback so we see:

  • that it really gets called when the response arrives
  • which arguments Ext.Direct passes to the callback

As you can see, the callback is called with two arguments:

  • response – it is that what is returned by the server-side Car.go() method. It can be string (as in our example), boolean, object, array or void (nothing).
  • e – it is Ext.Direct.Event object or, being more specific, Ext.Direct.RemotingEvent.

The event e has some useful properties and methods, most important of them are:

  • status is true if the call was successful, false if the call failed
  • result contains same value as the first argument – it is server response data
  • type is rpc in our example but it also can be exception or others
  • action is the class name
  • method is name of the method called
  • getTransaction() is method to retrieve the transaction used in this server round trip. You would use it if you want more data on the transaction.

Processing exceptions

Let’s call go method again:

Example.Car.go(300, console.info);

The callback is called as before but the arguments differ:

  • response is undefined – no data from server
  • e has type exception and has property message that contains error message text

An example application

That is almost all we need to know to start using Ext.Direct in an application. I’ve written a simple one so you have something to play with.

First, create file example.js with the following content:

/**
 * Mastering Ext.Direct example script
 *
 * @author     Ing. Jozef Sakalos
 * @copyright  (c) 2009, by Ing. Jozef Sakalos
 * @date       16. September 2009
 * @version    1.0
 * @revision   $Id$
 */
 
Ext.BLANK_IMAGE_URL='ext/resources/images/default/s.gif';
 
Ext.onReady(function() {
    /**
     * This function is called when Ext.Direct request
     * response arrives from the server.
     *
     * @param {String/Object/Array/Null} response 
     * That what is returned by server method
     * @param {Ext.Direct.RemotingEvent/Ext.Direct.ExceptionEvent} e 
     */
    var callback = function(response, e) {
 
        // uncomment if you want to inspect arguments in Firebug Console
//        console.log(response, e);
 
        var status = '<b>Success</b>'
        var text = '';
 
        // success handling - e.status is success flag: 
        // true is success, false is failure
        if(true === e.status) {
            // response argument is same as e.result
            text = response;
        }
 
        // failure handling
        else {
            status = '<b><i>Failure</i></b>'
 
            // in the case of an exception, we don't have response but message
            text = e.message;
        }
 
        // grab the center body
        var body = win.items.itemAt(1).body;
 
        // display the response
        body.createChild({
             tag:'div'
            ,cls:'response'
            ,html:status + ': ' + text
        });
 
        // scroll down
        body.scrollTo('top', 100000, true);
    };
 
 
    // create Ext.Direct test window
    var win = new Ext.Window({
         title:'Mastering Ext.Direct by Saki'
        ,width:600
        ,height:400
        ,closable:false
        ,layout:'border'
        ,border:false
        ,items:[{
            // west region with buttons
             region:'west'
            ,width:160
            ,minSize:160
            ,split:true
            ,defaults:{minWidth:120}
            ,layout:'table'
            ,bodyStyle:'padding:20px'
            ,layoutConfig:{columns:1, tableAttrs:{style:{width:'100%'}}}
            ,items:[{
                 xtype:'button'
                ,text:'Car.start()'
 
                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.start.createDelegate(null, [callback])
            },{
                 xtype:'button'
                ,text:'Car.go(80)'
 
                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.go.createDelegate(null, [80, callback])
            },{
                 xtype:'button'
                ,text:'Car.go(250)'
 
                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.go.createDelegate(null, [250, callback])
            },{
                 xtype:'button'
                ,text:'Car.stop()'
 
                // a delegate is needed if we want to pass arguments
                ,handler:Example.Car.stop.createDelegate(null, [callback])
            },{
                 xtype:'button'
                ,text:'Send All'
 
                // another option is inline function that executes calls
                ,handler:function() {
 
                    // the following calls will be combined in one request
                    Example.Car.start(callback);
                    Example.Car.go(80, callback);
                    Example.Car.go(250, callback);
                    Example.Car.stop(callback);
                }
            }]
        },{
            // responses are displayed here
             region:'center'
            ,autoScroll:true
            ,tbar:['->', {
                text:'Clear'
               ,handler:function(){win.items.itemAt(1).body.update('')}
            }]
        }]
    });
    win.show();
 
});
 
// eof

Then tune your index.php so that it reads:

<?require_once("config.php");?>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
  <script type="text/javascript" src="ext/adapter/ext/ext-base.js"></script>
  <script type="text/javascript" src="ext/ext-all-debug.js"></script>
  <title id="page-title">Mastering Ext.Direct by Saki</title>
  <style type="text/css">
      .x-table-layout-cell {
        height:40px;
        text-align:center;
        vertical-align:middle;
    }
    .x-table-layout-cell table {
        margin:auto
    }
    .response {
        padding:4px 0 4px 20px;
        font-size:13px;
    }
  </style>
  <script type="text/javascript" src="api.php"></script>
  <script type="text/javascript">
      Ext.Direct.addProvider(Example.API);
  </script>
  <script type="text/javascript" src="example.js"></script>
</head>
<body>
</body>
</html>

Conclusion

Good! Play with Ext.Direct and let me know what you would like to have in next parts.