事件
事件模型就是設計模式中的“觀察者模式”:當對象的狀態發生了變化,那麼這個對象可以將該事件通知其它對象。
爲了使用事件模型,需要實現這三個步驟:1、定義事件;2、註冊事件句柄;3、觸發事件。
JTool.php在protected/components 下
OK,功能已經實現了,找個控制器,執行
JTool.php在protected/components 下
class JTool extends CComponent{
private $_width;
public function getWidth(){
return $this->_width ? $this->_width : 1;
}
public function setWidth($width){ <------------觸發事件
if($this->hasEventHandler('onChange')){
$this->onChange(new CEvent());
}
$this->_width = $width;
}
public function onChange($event){ <----------定義事件
$this->raiseEvent('onChange', $event);
}
}
OK,功能已經實現了,找個控制器,執行
-----inside a controller
public function actionXXX()
{
$j = new JTool();
$j->onChange = array($this, "showChange"); //給事件綁定handle showChange <--------綁定事件
$j->width = 100; //調用setWidth,解發綁定的事件showChange <--------觸發事件
}
function
showChange() {
echo
'changed me'
;
}