最近跟蹤yii源碼 里面涉及到了綁定事件行為之類,于是自己手寫了一個最簡單的事件綁定實現(xiàn)
成都創(chuàng)新互聯(lián)公司網(wǎng)站建設由有經(jīng)驗的網(wǎng)站設計師、開發(fā)人員和項目經(jīng)理組成的專業(yè)建站團隊,負責網(wǎng)站視覺設計、用戶體驗優(yōu)化、交互設計和前端開發(fā)等方面的工作,以確保網(wǎng)站外觀精美、成都網(wǎng)站建設、網(wǎng)站制作易于使用并且具有良好的響應性。
class EventHandle { private static $_map = array(); //類似jquery綁定事件 public function on($name, $callback) { if(!is_callable($callback)) return false; if(!isset(self::$_map[$name])) { self::$_map[$name] = array(); } self::$_map[$name][] = $callback; } //觸發(fā)事件 public function trigger($name, $event) { if(!isset(self::$_map[$name])) return false; $function_arr = self::$_map[$name]; foreach($function_arr as $function) { call_user_func($function, $event); } return true; } //移除某個事件特定的回調(diào)函數(shù) public function remove($name, $callback) { if(!isset(self::$_map[$name])) return false; $map = self::$_map[$name]; $pos = array_search($callback, $map, true); if($pos >= 0) { array_splice($map, $pos, 1); self::$_map[$name] = $map; } return true; } } //事件對象 class Event { public static $options = array(); public function __construct($options = array()) { $this->options = $options; } } //通過函數(shù)當回調(diào)函數(shù) function start1($event) { echo 'start1asdaa
'; var_dump($event); } //通過類的方法當回調(diào)函數(shù) class EventCallback { public function start3($event) { echo 'start3
'; } } $eventhandle = new EventHandle(); $eventhandle->on('start', "start1"); $eventhandle->on('start', array("EventCallback", "start3")); $eventhandle->remove('start', array("EventCallback", "start3")); $eventhandle->trigger('start', new Event(array('name' => 'hhhh', 'age' => 25)));
出現(xiàn)的結果如下:
start1asdaa object(Event)[2] public 'options' => array (size=2) 'name' => string 'hhhh' (length=4) 'age' => int 25