jacob
jacob

Reputation: 2896

Is there a way to define model fields in function?

The normal way to define a model is as follows:

Ext.define('App.MyModel', {
    extend: 'Ext.data.Model',

    fields: [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'}
    ]
});

Is there a way to specify the fields (and perhaps all the config properties) inside an init-type method, similar to how a component's config can be set in initComponent()?

It would be useful to have this capability in order to do things like set local vars for certain repetitive properties.

Upvotes: 1

Views: 130

Answers (2)

radtad
radtad

Reputation: 189

You could also do something like this in initComponent. I use this sometimes when creating stores within a component passing in a variable based on whether or not I want the store to autoLoad.

Ext.define('App.MyModel', {
    extend: 'Ext.data.Model',
    initFields: function(fieldType) {
        return [
            {name: 'id', type: fieldType},
            {name: 'name', type: fieldType}
        ];
    },
    initComponent: function() {
        var me = this;

        Ext.apply(me, {
            fields: me.initFields('string')
        });
        me.callParent();
    }
});

Upvotes: 0

rixo
rixo

Reputation: 25001

You can define a function anywhere you want in Javascript!

Ext.define('App.MyModel', {
    extend: 'Ext.data.Model',

    fields: function() {
        return [
            {name: 'id', type: 'int'},
            {name: 'name', type: 'string'}
        ];
    }() // important: run it immediately!
});

Upvotes: 1

Related Questions