Wednesday, November 25, 2009

Reusable component template as given in the extjs.com documentation

A Re-usable Template

The following is a template (based on the template posted by Jozef Sakalos in mjlecomte's forum post) that you can use as a starting-point when extending Ext.Component classes

MyComponent = Ext.extend(Ext.some.component, {
// Prototype Defaults, can be overridden by user's config object
propA: 1,

initComponent: function(){
// Called during component initialization

// Config object has already been applied to 'this' so properties can
// be overriden here or new properties (e.g. items, tools, buttons)
// can be added, eg:
Ext.apply(this, {
propA: 3
});

// Before parent code

// Call parent (required)
MyComponent.superclass.initComponent.apply(this, arguments);

// After parent code
// e.g. install event handlers on rendered component
},

// Override other inherited methods
onRender: function(){

// Before parent code

// Call parent (required)
MyComponent.superclass.onRender.apply(this, arguments);

// After parent code

}
});

// register xtype to allow for lazy initialization
Ext.reg('mycomponentxtype', MyComponent);

As an enlightening example, if you used the above class via either of the following:

var myComponent = new MyComponent({
propA: 2
});
// Or lazily:
{..
items: {xtype: 'mycomponentxtype', propA: 2}
..}

then the property propA would have been set three times, to the values 1, 2, and 3 consecutively. If you follow the code (and the comments) through you will see that value starts as 1 (Prototype default) and then is set to 2 by the user's config object, and finally is overridden in initComponent and set to 3. Hopefully this example gives you a bit of insight into the order in which the code is executed (not in the order that you read it from start to finish!).

Because components nest other components, here's a quick way to grab the top-most component.

var topCmp = (function(o){while(o.ownerCt){o=o.ownerCt} return o;})(this);

More clearer and specific example


Application.PersonnelGrid = Ext.extend(Ext.grid.GridPanel, {
border:false
,initComponent:function() {
Ext.apply(this, {
store:new Ext.data.Store({...})
,columns:[{...}, {...}]
,plugins:[...]
,viewConfig:{forceFit:true}
,tbar:[...]
,bbar:[...]
});

Application.PersonnelGrid.superclass.initComponent.apply(this, arguments);
} // eo function initComponent

,onRender:function() {
this.store.load();

Application.PersonnelGrid.superclass.onRender.apply(this, arguments);
} // eo function onRender
});

Ext.reg('personnelgrid', Application.PersonnelGrid);

No comments:

Post a Comment