0
votes

My model has two data fields: persistent and calculated:

Ext.define('My.model.Value', {
    extend: 'Ext.data.Model',
    idProperty: 'id',
    fields: [
        { name: 'id', type: 'auto' },
        { name: 'percentage', type: 'float' }, // values in 0..1 range
        { name: 'percentageDecimal', type: 'float', persist: false,
            calculate: function(v) {
                v = v.percentage;
                return Ext.isNumber(v) ? v * 100.0 : v;
            }
        }
    ]
});

The percentageDecimal field is used in a grid and it is editable.

Question: how can I change my model to automatically update percentage field everytime the percentageDecimal is updated?

I use ExtJs 5.0.1.

3

3 Answers

2
votes

I used @adaskos' suggestion as follows:

Ext.define('My.model.Value', {
    extend: 'Ext.data.Model',
    idProperty: 'id',
    fields: [
        { name: 'id', type: 'auto' },
        { name: 'percentage', type: 'float' }, // values in 0..1 range
        { name: 'percentageDecimal', type: 'float', persist: false,
            calculate: function(v) {
                v = v.percentage;
                return Ext.isNumber(v) ? v * 100.0 : v;
            }
        }
    ],
    set: function (fieldName, value, options) {
        if (Ext.isString(fieldName)) {
            // single field update
            if (fieldName === 'percentageDecimal') {
                this.set('percentage', Ext.isNumber(value) ? 0.01 * value : value);
                return;
            }
        } else {
            // multiple fields update
            if (Ext.isDefined(fieldName.percentageDecimal)) {
                var data = Ext.clone(fieldName);
                data.percentage = Ext.isNumber(data.percentageDecimal) 
                  ? 0.01 * data.percentageDecimal 
                  : data.percentageDecimal;
                delete data.percentageDecimal;
                this.set(data);
                return;
            }
        }
        this.callParent(arguments);
    }
});
1
votes

I don't know if they added an automated way to do this in 5.0.1, but you can always override the set method and whenever an update occurs to percentageDecimal, you recalculate the percentage.

An alternative I prefer: if you expect enough updates but all you want is to display it in a grid, you can remove the extra computed field from the model and set your column with dataIndex: 'percentageDecimal' and change its renderer function to display it as you like (as a decimal).

Like below:

... , { text: 'Percentage', dataIndex: 'percentageDecimal'
    , renderer: function (v) {
        return Ext.isNumber(v) ? v * 100.0 : v;
    }
  }
1
votes

You should use the config options depends to have this updated automatically! And use the function convert instead of calculate (not sure if it work with calculate, i need to test)

See http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext.data.field.Field-cfg-depends