qiang, on 27 March 2012 - 10:47 PM, said:
// attach an anonymous function to the 'click' event
$button->on('click', function($event) { ... });
// trigger the 'click' event
$button->trigger('click', new Event($this));
// detaches $callback from 'click'
$button->off('click', $callback);
// returns event handlers of 'click' as a vector object so that we can manipulate it
$handlers = $button->getEventHandlers('click');
Just curious: is "trigger" really public? Or was this just for demonstration purpose? I implemented it as protected, because I can't see a reason why events should be triggered from outside.
Can you please include the event name in the "Event" object when it gets triggered? Would be helpful in cases where one event handler is attached to several events.
Third, I think the second parameter of trigger can be made optional:
class Button extends Component
{
public function foo()
{
$this->trigger('fooEvent');
}
public function bar()
{
$this->trigger('barEvent', new DerivedEvent);
}
public function baz()
{
$this->trigger('bazEvent', array(
'eventParamKey' => 'eventParamValue',
));
}
}
class Component
{
protected function trigger( $eventName, $event=null )
{
if ($event === null)
{
$event = new Event();
}
else if (is_array($event))
{
$params = $event;
$event = new Event();
$event->params = $params;
}
if ($event instanceof Event)
{
$event->sender = $this;
$event->name = $eventName;
}
else
{
throw new Exception( "Invalid param" );
}
// Event prepared, start your event dispatching logic.
}
}
Maybe not even hard code the "Event" class, but provide a way to configure the default event class that will be created (must derive from Event).
Don't like ads in my sig...