Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Observable implements IObservable
- {
- protected $_events = Array();
- function __construct()
- {
- }
- /**
- * registerEvents('fooEvent');
- * registerEvents(Array('fooEvent','barEvent'));
- */
- function registerEvents($events)
- {
- if ( !is_array($events) ) $events = Array($events);
- foreach ( $events as $eventId ){
- if ( isset($this->_events[$eventId]) )
- throw new Exception("Event already registered: $eventId");
- $this->_events[$eventId] = Array();
- }
- }
- function isRegistered($eventId)
- {
- return isset($this->_events[$eventId]);
- }
- /**
- * on('click','myFunction');
- * on('click','myFunction',$this);
- * on('click','myFunction',$this,$customArguments);
- */
- function on($eventId,$callback,$context=null,$addArg=null)
- {
- if ( !isset($this->_events[$eventId]) )
- throw new Exception("Event not registered: $eventId");
- $handler = $this->_makeHandler($callback,$context,$addArg);
- $this->_events[$eventId][] = $handler;
- }
- function un($eventId,$callback,$context=null,$addArg=null)
- {
- if ( !isset($this->_events[$eventId]) )
- throw new Exception("Event not exists: $eventId");
- $handler = $this->_makeHandler($callback,$context,$addArg);
- foreach ( $this->_events[$eventId] as $index => $h )
- {
- if ( $h === $handler )
- {
- unset($this->_events[$eventId][$index]);
- }
- }
- }
- /**
- * fireEvent($eventId)
- * fireEvent($eventId,$arg1,$arg2,...,$argX)
- */
- function fireEvent($eventId)
- {
- if ( func_num_args() < 1 )
- throw new Exception('At least one argument required');
- $args = func_get_args();
- $eventId = $args[0];
- array_shift($args);
- if ( !isset($this->_events[$eventId]) )
- throw new Exception("Event not registered: $eventId");
- foreach ( $this->_events[$eventId] as $handler )
- {
- $callback = $handler[0];
- $resultArgs = $args;
- if ( $handler[1] === null )
- {
- $resultArgs = $args;
- }else
- if ( is_array($handler[1]) )
- {
- $resultArgs = array_merge($args,$handler[1]);
- }else
- {
- $resultArgs = $args;
- $resultArgs[] = $handler[1];
- }
- $result = call_user_func_array($callback,$resultArgs);
- if ( $result === false ) return false;
- }
- return true;
- }
- function _makeHandler($callback,$context=null,$void=null)
- {
- if ( !is_string($callback) )
- throw new Exception('Callback must be a string value');
- if ( $context ) $callback = Array($context,$callback);
- return Array($callback,$void);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment