日期:2014-05-16  浏览次数:20373 次

[Ext JS 4] 实战之Grid, Tree Gird 动态添加列

前言

在Ext js 中, 定义一个Grid 很方便,主要需要的是

1. 定义columns

2. 定义一个store

3. 定义grid

var store1 = Ext.create('Ext.data.TreeStore', {
  fields: ['task1','task2','task3'],
    root:{
          "text": ".",
          "children": [{'task1':'11','task2':'22','task3':'33'}]
    }
});
  var treeGrid1 = Ext.create('Ext.tree.Panel',{
  header: 'Test Grid',
  renderTo: Ext.getBody(),
  collapsible: true,
  rootVisible: false,
  autoScroll: true,
  height: 600,
  store: store1,
  columns: [{"text":"Task 1","dataIndex":"task1"},
            {"text":"Task 2","dataIndex":"task2"},
            {"text":"Task 3","dataIndex":"task3"}]      
});

以上是一个最简单的例子。


如何动态添加列

要动态添加一列, 也很简单

使用 Grid 的 reconfigure 方法就可以了。

var cols1 = [{"text":"Task 1","dataIndex":"task1"},
            {"text":"Task 2","dataIndex":"task2"},
            {"text":"Task 3","dataIndex":"task3"}
          ];
var store1 = Ext.create('Ext.data.TreeStore', {
  fields: ['task1','task2','task3'],
    root:{
          "text": ".",
          "children": [{'task1':'11','task2':'22','task3':'33'}]
    }
});
  var treeGrid1 = Ext.create('Ext.tree.Panel',{
  header: 'Test Grid',
  renderTo: Ext.getBody(),
  collapsible: true,
  rootVisible: false,
  autoScroll: true,
  height: 600,
  store: store1,
  columns: cols1      
});

  //dynamic add col
  cols1.push({"text":"Task 4","dataIndex":"task4"});
  treeGrid1.reconfigure(store1,cols1);

也很简单。


双击编辑某行

配置行编辑的plugin 为Ext.grid.plugin.RowEditing, 设置某列编辑的editor

var cols1 = [{"text":"Task 1","dataIndex":"task1"},
            {"text":"Task 2","dataIndex":"task2",editor:{xtype:"textfield"}},
            {"text":"Task 3","dataIndex":"task3"}
          ];
var store1 = Ext.create('Ext.data.TreeStore', {
  fields: ['task1','task2','task3'],
    root:{
          "text": ".",
          "children": [{'task1':'11','task2':'22','task3':'33'}]
    }
});
  var treeGrid1 = Ext.create('Ext.tree.Panel',{
  header: 'Test Grid',
  renderTo: Ext.getBody(),
  collapsible: true,
  rootVisible: false,
  autoScroll: true,
  height: 600,
  store: store1,
  columns: cols1,
  plugins:[Ext.create('Ext.grid.plugin.RowEditing', {
	    clicksToMoveEditor: 2,
	    autoCancel: false
	})]
});

  //dynamic add col 
  cols1.push({"text":"Task 4","dataIndex":"task4"});
  treeGrid1.reconfigure(store1,cols1);

同样很简单。

下面要进入重点了