原文地址 文章日期:2006/09/04
新組件Gird包含了許多的類和繼承方法。如果讀者不是太熟悉的面向對象開發的話,可能會對一個變量如何從某個類得到繼承的方法感到困惑,用起GIRD來感到困難。在YAHOO.ext.gird包中,大多數類是設計成為“即插即用plug and play”的,可擴展的extended和可自定義的customized,能以最小量的代碼插入輕松到web程序中。
要測試和創建一個實現gird的范例,我決定做一個簡單的,只有一頁的RSS種子采集器RSS Feed Viewer。整個程序寫了100行代碼而其中有20行是關于gird的。這個范例說明了gird的一些典型功能,如Ajax loading,預處理(preprocessing)和自定義渲染(custom rendering)
這里嵌入了個迷你型程序(用iframe)
我一步一步手把手帶你進入GIRD,還會支持哪些是關鍵的地方,哪些不是。
Step 1 創建柱模型ColumnModel
var myColumns = [ {header: "Title", width: 350, sortable: true}, {header: "Date", width: 125, sortable: true, renderer: formatDate}];var colModel = new YAHOO.ext.grid.DefaultColumnModel(myColumns);
GRID從柱模型中取得某一列的信息。在這個例子我們調用一個默認的柱模型(稱DefaultColumnModel),一個包含所有相關的信息的對象。對象的屬性如下:
header: - 表頭 width: - 寬度 sortable: - true=可排序 renderer: - 指定渲染方式。調用函數參數為 (value, rowIndex, columnIndex),并由函數返回(return)值來顯示到單元格cell中。 sortType: - 指定排序方式。參見文檔資料,有5到6種的轉換方式。除header和width其它為可選的
創建DataModel數據模型
var schema = { tagName: 'item', id: 'use-index', fields: ['title', 'pubDate']};this.dataModel = new YAHOO.ext.grid.XMLDataModel(schema);this.dataModel.addPreprocessor(1, parseDate); //列1是日期,先預處理一下this.dataModel.onLoad.subscribe(this.onLoad, this, true);this.dataModel.onLoadException.subscribe(this.showError, this, true);this.dataModel.setDefaultSort(colModel, 1, 'ASC');
DataModel是GIRD的數據來源。所有在 YAHOO.ext.grid包中的DataModels,都有一系統通知UI改變內容的事件。也就是說你可以改變model內的數據,而同時對UI自動映射。
這個范例中我們使用XMLDataModel。XMLDataModel提供一個簡易的方式來映射XML文檔與gird之間的結構。你所要做的是寫個簡單的schema,讓model知道有哪些column給gird。Schema有下列屬性:
tagName: - Model會讀取這一節點下(tagName)的所有子節點(items的上一層節點名稱); id: - The attribute or child element to match to get the id of the row. If an attribute or child element is not found with the supplied "id" name, the index of the record is used. So if you don't have a specific id attribute, just use something like 'use-index' which won't be matched and the index will be used. fields: - An array of attribute names or child node tag names to match for the column values. If you have 4 columns in your ColumnModel, you should have 4 items in your fields array. If a name specified in the array isn't found, an empty string is used.新聞熱點
疑難解答