您好,登錄后才能下訂單哦!
最近跟蹤yii源碼 里面涉及到了綁定事件行為之類,于是自己手寫了一個最簡單的事件綁定實現
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; } //觸發事件 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; } //移除某個事件特定的回調函數 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; } } //通過函數當回調函數 function start1($event) { echo 'start1asdaa<br>'; var_dump($event); } //通過類的方法當回調函數 class EventCallback { public function start3($event) { echo 'start3<br>'; } } $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)));
出現的結果如下:
start1asdaa object(Event)[2] public 'options' => array (size=2) 'name' => string 'hhhh' (length=4) 'age' => int 25
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。