8
* This traits contains all the basic functions to implement an
9
* EventEmitterInterface.
11
* Using the trait + interface allows you to add EventEmitter capabilities
12
* without having to change your base-class.
14
* @copyright Copyright (C) 2013 fruux GmbH. All rights reserved.
15
* @author Evert Pot (http://evertpot.com/)
16
* @license https://raw.github.com/fruux/sabre-event/master/LICENSE
18
trait EventEmitterTrait {
21
* The list of listeners
25
protected $listeners = [];
28
* Subscribe to an event.
30
* @param string $eventName
31
* @param callable $callBack
32
* @param int $priority
35
public function on($eventName, callable $callBack, $priority = 100) {
37
$listeners =& $this->listeners($eventName);
38
$listeners[] = [$priority, $callBack];
39
usort($listeners, function($a, $b) {
48
* Subscribe to an event exactly once.
50
* @param string $eventName
51
* @param callable $callBack
52
* @param int $priority
55
public function once($eventName, callable $callBack, $priority = 100) {
58
$wrapper = function() use ($eventName, $callBack, &$wrapper) {
60
$this->removeListener($eventName, $wrapper);
61
$result = call_user_func_array($callBack, func_get_args());
65
$this->on($eventName, $wrapper);
72
* This method will return true if 0 or more listeners were succesfully
73
* handled. false is returned if one of the events broke the event chain.
75
* @param string $eventName
76
* @param array $arguments
79
public function emit($eventName, array $arguments = []) {
81
foreach($this->listeners($eventName) as $listener) {
83
$result = call_user_func_array($listener[1], $arguments);
84
if ($result === false) {
95
* Returns the list of listeners for an event.
97
* The list is returned as an array. Every item is another array with 2
98
* elements: priority and the callback.
100
* The array is returned by reference, and can therefore be used to
101
* manipulate the list of events.
103
* @param string $eventName
106
public function &listeners($eventName) {
108
if (!isset($this->listeners[$eventName])) {
109
$this->listeners[$eventName] = [];
112
return $this->listeners[$eventName];
117
* Removes a specific listener from an event.
119
* @param string $eventName
120
* @param callable $listener
123
public function removeListener($eventName, callable $listener) {
125
$listeners =& $this->listeners($eventName);
126
foreach($listeners as $index => $check) {
127
if ($check[1]===$listener) {
128
unset($listeners[$index]);
136
* Removes all listeners from the specified event.
138
* @param string $eventName
141
public function removeAllListeners($eventName) {
143
$listeners =& $this->listeners($eventName);