Yii学习第三天-Event

事件
事件模型就是设计模式中的“观察者模式”:当对象的状态发生了变化,那么这个对象可以将该事件通知其它对象。
为了使用事件模型,需要实现这三个步骤:1、定义事件;2、注册事件句柄;3、触发事件。

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'
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章