PDA

View Full Version : Best Practice in object construction



lrayman
27 Jun 2013, 10:45 AM
My apologies for a somewhat long-winded preamble to a fairly straightforward question:

I have a grid with some columns that have common renderer pattern. So I wrote a renderer factory function that returns a renderer that does a table lookup:

Ext.define('My.common',{
rendererFactory : function (lookupMap) {
// return a function that does a map lookup
// func should return the default if key not found in map
return function (key) {
if (lookupMap.hasOwnProperty(key)) {
return lookupMap[key];
} else {
return key;
}
};
}
});

I was hoping to define the lookup tables as properties of the grid

Ext.define('My.view.OrderGrid',{
extend: 'Ext.grid.Panel',
...
lookupMap: { k1:'val1', k2:'val2', ... },
...
columns: [
{ text: 'Column A', dataIndex: 'colA', renderer: My.common.rendererFactory(this.lookupMap) }



This, of course, does not work. There is no "this" reference when the column definitions are being read.

At first, I had to put the lookupMap definition inline in the call to the rendererFactory function. Eventually, I had to initialize some more complex functions/tables in an anonymous wrapper function around my grid object:


(function () {
var complexRendererFactory = function(args, lookupTable) {
// return a renderer function that calls the base RendererFactory
var baseRenderFunc = My.common.RendererFactory(lookupTable);
return function(value, meta, record) {
var key = // complex logic based on args...
return baseRenderFunc(record.get(key));
};
};
var lookupMap1 = { k11:'val11', k12:'val12', ... }
var lookupMap2 = { k21:'val21', k22:'val22', ... }

Ext.define('My.view.OrderGrid',{
extend: 'Ext.grid.Panel',
...
columns: [
{ text: 'Column A', dataIndex: 'colA', renderer: complexRendererFactory(args, lookupMap1) }
{ text: 'Column B', dataIndex: 'colB', renderer: complexRendererFactory(args, lookupMap2) }
...
]
});
})();


My question is: is there a "best practice" for complex object initialization? Is there a way to do it without the anonymous function? I'm sure I'm not the first programmer to come across this problem...

Thanks

slemmon
1 Jul 2013, 12:50 PM
First thing that occurred to me after reading the examples was to do something like:



renderer: function (v, m, r, i, c, s, view) {
My.common.rendererFactory(view.ownerCt.lookupMap)
}