Sunday, May 22, 2011

extjs extend jsonstore

The problem: in an extjs application, we may have multiple jsonstores with same settings, and we don't want to repeat all these settings everytime we create a new jsonstore instance. For example, in my extjs application, all jsonstores have the following settings:

messageProperty : 'message',
successProperty   : 'result',
root                      : 'data'

And we want these settings to be default so we don't have to repeat them.

We actually can have two solutions to this problem.
Solution one: We can create a function that generate a jsonstore instance:

var getJsonStore = function(config) {
                return new Ext.data.JsonStore(Ext.apply({
                                messageProperty : 'message',
                                successProperty : 'result',
                                root : 'data'
                }, config));
}

With this solution, everytime you need a jsonstore, you call getJsonStore(customisedConfig);

What if we want to do lazy instantiation? For example, we want to do this:
{
xtype : 'jsonstore'
}

This comes to the second solution: extending jsonstore
Solution two: Extending jsonstore using Ext.extend
But extending jsonstore is a little different from extending other extjs components, because some properties like 'root', 'messageProperty' are actually NOT the config options of jsonstore. They are the config options of a jsonreader inside jsonstore. So you can't simply use Ext.extend. The following code will NOT work:

MyJsonStore = Ext.extend(Ext.data.JsonStore, {
    messageProperty : 'message',
    successProperty : 'result',
    root            :  'data',
    initComponent : function() {
        MyJsonStore.superclass.initComponent.call(this);
    }
});
Ext.reg('myjsonstore',MyJsonStore);

Instead, we have to do it in this way:

MyJsonStore = Ext.extend(Ext.data.JsonStore, {
            constructor : function(config) {
                        var baseConfig = {
                                    messageProperty : 'message',
                                    successProperty : 'result',
                                    root : 'data'
                        };

                        MyJsonStore.superclass.constructor.call(this, Ext.apply(baseConfig, config));
            }
});

Ext.reg('myjsonstore', MyJsonStore);

And now, we can do lazy instantiation:
{
xtype:'myjsonstore'
}

1 comment:

蜗牛 said...

Thank you very much