對于包含多Item的用戶界面組件(UI Component)(如Tree, Table, DataGrid等) Item 容器來說,其行為大多固定,需要時常改變的是Item的顯示。如果將顯示實現放在這些item containers的class內,那么不僅這些classes的可重復利用性受到破壞,代碼也難以管理。這時應該考慮將item的顯示邏輯分離出來。
具體實現方法: 將item顯示邏輯獨立出來放到item render class/function中。
這種模式在Java Swing及Flex的API中有大量的使用。在這里舉一個PHP的例子。在網站制作時,我們使用如下的HTML代碼搭配CSS來顯示導航:
<ul>
<li ><a href="A.php">A</a>
<ul><li ><a href="A1.php">A1</a></li><li ><a href="A2.php">A2</a></li></ul>
<li ><a href="B.php">B</a>
<ul><li ><a href="B1.php">B1</a></li><li ><a href="B2.php">B2</a></li></ul>
<li ><a href="C.php">C</a>
<ul><li ><a href="C1.php">C1</a></li><li ><a href="C2.php">C2</a></li></ul>
</ul>
在PHP中,我們使用Node來為如上的tree建模 - 有一個頂級的虛擬Node, 然后回溯打印即可。為了美化頁面,這時我們想讓第一級的Node顯示圖片,讓其他級的保留使用文字。這時我們使用如下的render function:
// node class中:
public function toHtmlMenu($printThis = true, $printSubItemsLevel = 100, $renderFuncForListItemContent = NULL) {
if($printThis) {
$s = "<li>";
if($renderFuncForListItemContent == null) {
$s .= "<a href=/"$this->path/">" . $this->getLabel(). "</a>";
}else{
$s .= call_user_func($renderFuncForListItemContent, $this, $selectIndex, $language, $country);
}
}
// recursive print ...
}
// in caller script:
function menuItemRenderLevel1AsImage(MenuItem $menuItem) {
if($menuItem->getLevel() == 1) {
return "<a href=/"" . $menuItem->getPath() . "/">" . "<img src=/"$menuItem->id.png/">" . "</a>";
}else{
return "<a href=/"$this->path/">" . $this->getLabel(). "</a>";
}
}
$menuCode = $MENU_ROOT->toHtmlMenu(false, 2, "menuItemRenderLevel1AsImage");
新聞熱點
疑難解答