我正在使用 CardLayout 在具有多个节点的全屏面板之间切换。为了最大限度地减少内存使用,我想在隐藏卡片时销毁它,并且仅在显示卡片时重新创建它(从配置对象)。
如果您查看下面的“切换卡”按钮处理程序,您将了解我目前是如何实现这一目标的。然而,这看起来很笨拙(使用 ComponentMgr 实例化卡,将其添加到容器中,删除旧卡等)。有更好的方法来实现这一点吗?再说一遍,我的主要目标是在卡片不可见时将其销毁。
谢谢!
var panel1Cfg = {
id: 'card-1',
xtype: 'panel',
html: 'Card 1',
listeners: {
render: function() { console.log('render card 1'); },
beforedestroy: function() { console.log('destroying card 1'); }
}
};
var panel2Cfg = {
id: 'card-2',
xtype: 'panel',
html: 'Card 2',
listeners: {
render: function() { console.log('render card 2'); },
beforedestroy: function() { console.log('destroying card 2'); }
}
};
var cardPanel = new Ext.Panel({
renderTo: document.body,
layout: 'card',
items: [ panel1Cfg ],
activeItem: 0,
itemCfgArr: [ panel1Cfg, panel2Cfg ],
activeItemCfgIndex: 0,
tbar: [
{
text: 'Switch Cards',
handler: function() {
var cardToRemove = cardPanel.getLayout().activeItem;
// Figure out which panel create/add/show next
cardPanel.activeItemCfgIndex = (cardPanel.activeItemCfgIndex + 1) % cardPanel.itemCfgArr.length;
// Use cfg to create component and then add
var cardToShow = Ext.ComponentMgr.create(cardPanel.itemCfgArr[cardPanel.activeItemCfgIndex]);
cardPanel.add(cardToShow);
// Switch to the card we just added
cardPanel.getLayout().setActiveItem(1);
// Remove the old card (console should show 'destroy' log msg)
cardPanel.remove(cardToRemove);
}
}
]
});
最佳答案
我认为一个更优雅的解决方案是创建一个类来包装您的配置,并在激活/停用时处理创建/销毁。这样,您的卡片布局就不需要了解这种特殊处理,并且您可能会混合被破坏的卡片和没有被破坏的卡片。您还可以在其他布局中重用此行为,例如 TabPanel
,甚至 AccordianLayout
。
你的类可能看起来像这样:
CleanPanel = Ext.extend(Ext.Panel, {
/** @cfg panelCfg - configuration for wrapped panel */
panelCfg: null,
layout: 'fit',
autoDestroy: true,
initComponent: function() {
CleanPanel.superclass.initComponent.call(this);
this.on({
scope: this,
activate: this.createPanel,
deactivate: this.destroyPanel
});
},
createPanel: function() {
this.add(this.panelCfg);
},
destroyPanel: function() {
this.removeAll();
}
});
将其中几个添加到您的主面板中,包装您的 panel1Cfg
和 panel2Cfg
,将您的 activeItem
切换逻辑保留在主面板中,它应该工作得很好。可能需要解决一些初始化细节,但您已经明白了。
祝你好运!
关于ExtJS:隐藏时销毁卡、显示时实例化的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5913375/