Tapestry Components
通用PropertySelection
示例代碼:svn://portal/private/wen/tapestry/common-property-selection
- 需要一個通用bo 的接口Selectable ,被選的對象要實作這個接口
- 需要通用模型類 SelectableModel
實體模組化時,如果一個bo 是另一個BO 的屬性,界面上需要儲存BO時需要參考選擇一個bo,bo 就需要實作Selectable 接口
public class Department extends BaseObject implements Selectable {
}
Selectable 接口如下:
public interface Selectable {
public Long getId();
public void setId(Long id);
public String getName();
public void setName(String name);
}
在BO 操作的Form 頁面上類,要有bo 對象(就是有getter setter)
public abstract Selectable getDepartment();
public abstract void setDepartment(Selectable department);
bo 的待選内容怎樣來的呢?要在BO 操作的Form 頁面上類裡做如下處理:
- 定義一個IPropertySelectionModel 屬性選擇模型
- 将bo 的清單放到這個模型中
- 頁面不存在了,可以将模型設為空
private IPropertySelectionModel availDepts = null;
public IPropertySelectionModel getAvailDepts() {
if (null == availDepts) {
availDepts = new SelectableModel(服務對象.getDepts());
}
return availDepts;
}
public void pageDetached(PageEvent pageEvent) {
availDepts = null;
}
這個模型基本是通用的,不用再自己寫了,使用bo 清單new 出來就行了
public class SelectableModel implements IPropertySelectionModel, Serializable {
private static final long serialVersionUID = 3528841813175496347L;
protected List itemList;
public SelectableModel(List list) {
itemList = list;
}
public int getOptionCount() {
return itemList.size();
}
public Object getOption(int index) {
return itemList.get(index);
}
public String getLabel(int index) {
return ((Selectable) itemList.get(index)).getName();
}
public String getValue(int index) {
return Integer.toString(index);
}
public Object translateValue(String value) {
return getOption(Integer.parseInt(value));
}
}
最後在頁面上定義元件,元件類型為PropertySelection,綁定兩個參數,value 為bo,model 為屬性選擇模型<component id="deptSelect" type="PropertySelection"> <binding name="value" value="department"></binding>
<binding name="model" value="availDepts"></binding>
</component>
- <component id="deptSelect" type="PropertySelection">
- <binding name="value" value="department"/>
- <binding name="model" value="availDepts"/>
- </component>
PropertySelection 元件設定預設值
例子:
在.page定義了如下元件:
<component id="departmentSelect" type="PropertySelection">
xml 代碼
- <component id="departmentSelect" type="PropertySelection">
- <binding name="value" value="department"/>
- <binding name="model" value="availDepts"/>
- </component>
<binding name="value" value="department"></binding>
<binding name="model" value="availDepts"></binding>
</component>
隻要在頁面類中,設定department的初始值,該值就是選中的預設值。
原因:當該元件周遊'model' availDepts時,會使用public Object getOption(int index)方法讀出清單,當 讀出的對象與'value'中的值相等時,就選中該項。 哈哈..簡單吧!:)