最近跟踪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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。