View Full Version : Replace component function

26 May 2011, 1:38 PM
In case you need to replace a component with new one, here's the addition to AbstractContainer that will allow such action:

Ext.override(Ext.AbstractComponent, {
replace: function(newCmp) {
var oldCmp = this,
parent = oldCmp.up(), //find the parent component

//find the exact position of the component that needs to be replaced
parent.items.each(function(c,i) {if (c==oldCmp) index=i;});

//remove the sucker
parent.remove(oldCmp, true);

//add the new one
newCmp = parent.insert(index, newCmp);

//refresh layout

//return the newly created component
return newCmp;

All you need to do is find the component you want to replace and - replace it:

Ext.getCmp('iNeedToBeReplaced').replace({xtype: 'panel',html:'I just replaced that old component'});

19 Jul 2013, 4:41 AM
I created something similar.

Ext.override(Ext.Component, {
replaceCompoment: function(oldEle, newEle) {
if (!oldEle || !newEle) { return; }

var ownerCt = oldEle.ownerCt,
position = ownerCt.items.indexOf(oldEle);

ownerCt.insert(position, newEle);

Probably it can be improved, but for the moment it is doing it's job just fine.

21 Jul 2013, 10:42 PM

thanks for your contribution.

Just 2 cents:

I personally do not prefer such methods on components that handle container stuff, because it implies that these components are within containers, and not floating or just rendered to dom. And it implies that components know their container, what is right since all have their ownerCt property, but what they do not need to know and IMO what we should not expect.

I would rather prefer an extension to Ext.container.AbstractContainer called replaceChild(oldChild, newChild, autoDestroy) or something like that which of course handles the case that oldChild is not part of this container.