http://www.extjs.com/forum/showthread.php?53009-Adding-removing-fields-and-columns提供了一个非常好的对GridPanel动态添加列的方法。但经过测试发现有一点小bug,就是在enableColumnMove为true的时候,动态添加的这些column行为异常。
稍加修改如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Ext.override(Ext.grid.ColumnModel, {
addColumn: function(column, colIndex) {
if (typeof column == 'string') {
column = { header: column, dataIndex: column };
}
var config = this.config;
this.config = [];
if (typeof colIndex == 'number') {
config.splice(colIndex, 0, column);
//handling the id of config to fulfill the drag&drop (when enableColumnMove is true) problem
for (var i = colIndex + 1; i < config.length; i++)
{
var id = config[i].id;
if (typeof id == 'number') {
config[i].id++;
}
}
} else {
colIndex = config.push(column);
}
this.setConfig(config);
return colIndex;
},
removeColumn: function(colIndex) {
var config = this.config;
this.config = [config[colIndex]];
config.splice(colIndex, 1);
//handling the id of config to fulfill the drag&drop (when enableColumnMove is true) problem
for (var i = colIndex + 1; i < config.length; i++)
{
var id = config[i].id;
if (typeof id == 'number') {
config[i].id--;
}
}
this.setConfig(config);
}
});
ColumnModel是根据config中的id来排序的,所以修正如上。
完整代码见原贴。
需要注意的是,这里假设动态添加column之前没有拖动过原有列,例如初始加载时。所以如果需求是拖动后再添加,需要稍微复杂一点的代码,基本概念就是id不要重复即可。可以参考源码中的
Ext源码中的Ext.grid.HeaderDropZone.onNodeDrop方法。