PDA

View Full Version : model.convert() not called when accessing field via model.get()



chaddjohnson
5 Feb 2013, 1:05 PM
I have the following model:

(function() {

var fourDecimals = function(value, record) {
return parseFloat(value.toFixed(4));
}

Ext.define('App.model.Stock', {
extend: 'Ext.data.Model',
fields: [
{name: 'Symbol', type: 'string'},
{name: 'TradePrice', type: 'float'},
{name: 'Bid', type: 'float'},
{name: 'Ask', type: 'float'},
{name: 'Volume', type: 'int'},
{name: 'TodaysClose', type: 'float'},
{name: 'PreviousClose', type: 'float'},
{
name: 'PriceChange',
type: 'float',
convert: function(value, record) {
return parseFloat((record.get('TradePrice') - record.get('PreviousClose')).toFixed(4));
}
},{
name: 'PercentPriceChange',
type: 'float',
convert: function(value, record) {
return parseFloat((((record.get('TradePrice') / record.get('PreviousClose')) - 1) * 100).toFixed(2));
}
}
]
});

})();


When I call do the following, the convert() function is not called for my model instance:



model.set('TradePrice', 12.34);
var priceChange = model.get('PriceChange');


Is this a bug?

chaddjohnson
7 Feb 2013, 11:32 AM
This does work in Sencha Touch 2. When a field that a convert() function depends on is updated, the convert() function is called.

I found a workaround based on this blog post (http://flexblog.faratasystems.com/2012/02/07/computed-fields-in-extjs-models-via-convert-functions):



set: function(fieldName, newValue) {
this.callParent(arguments);

// Force recalculation of dependent fields.
if (typeof fieldName == 'object' || fieldName == 'TradePrice' || fieldName == 'PreviousClose') {
this.set('PriceChange');
this.set('PercentPriceChange');
}
}


I added that to the model.