Grid
Grid是Ext中人们最想先睹为快的和最为流行Widgets之一。好,让我们看看怎么轻松地创建一个Grid并运行。
Ext.onReady(function() {
var myData = [
['Apple',29.89,0.24,0.81,'9/1 12:00am'],
['Ext',83.81,0.28,0.34,'9/12 12:00am'],
['Google',71.72,0.02,0.03,'10/1 12:00am'],
['Microsoft',52.55,0.01,0.02,'7/4 12:00am'],
['Yahoo!',29.01,0.42,1.47,'5/22 12:00am']
];
var myReader = new Ext.data.ArrayReader({}, [
{name: 'company'},
{name: 'price', type: 'float'},
{name: 'change', type: 'float'},
{name: 'pctChange', type: 'float'},
{name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
]
);
var grid = new Ext.grid.GridPanel({
store: new Ext.data.Store({
data: myData,
reader: myReader
}),
columns: [
{header: "Company", width: 120, sortable: true, dataIndex: 'company'},
{header: "Price", width: 90, sortable: true, dataIndex: 'price'},
{header: "Change", width: 90, sortable: true, dataIndex: 'change'},
{header: "% Change", width: 90, sortable: true, dataIndex: 'pctChange'},
{header: "Last Updated", width: 120, sortable: true,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
dataIndex: 'lastChange'}
],
viewConfig: {forceFit: true},
renderTo: 'content',
title: 'My First Grid',
width: 500,
frame: true
});//grid
grid.getSelectionModel().selectFirstRow();
});
这看上去很复杂,但实际上加起来,只有四行代码(不包含测试数据的代码)。
- 第一行创建数组并作为数据源。实际案例中,你很可能从数据库、或者WebService那里得到动态的数据。
- 接着,我们创建并加载data store, data store将会告诉Ext的底层库接手处理和格式化这些数据。不同的数据类型须在类Reader中指明。
- 接着,我们创建一个Grid的组件,传入各种的配置值,有:
- 新的data store, 配置好测试数据和reader
- 列模型column model定义了 列columns的配置
- 其他的选择指定了Grid所需的功能
- 最后,通过SelectionModel告诉Grid高亮显示第一行。
如果一切顺利,完成之后你会看到像这样的: