4 * Versatile event system similar to the WCF-PHP counter part.
6 * @author Alexander Ebert
7 * @copyright 2001-2015 WoltLab GmbH
8 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
9 * @module WoltLab/WCF/Event/Handler
11 define(['Dictionary'], function(Dictionary
) {
12 var _listeners
= new Dictionary();
17 function EventHandler() {};
18 EventHandler
.prototype = {
20 * Adds an event listener.
22 * @param {string} identifier event identifier
23 * @param {string} action action name
24 * @param {function(object)} callback callback function
25 * @return {string} uuid required for listener removal
27 add: function(identifier
, action
, callback
) {
28 if (typeof callback
!== 'function') {
29 throw new TypeError("[WoltLab/WCF/Event/Handler] Expected a valid callback for '" + action
+ "@" + identifier
+ "'.");
32 var actions
= _listeners
.get(identifier
);
33 if (actions
=== null) {
34 actions
= dictionary
.create();
35 _listeners
.set(identifier
, actions
);
38 var callbacks
= actions
.get(action
);
39 if (callbacks
=== null) {
40 callbacks
= dictionary
.create();
41 actions
.set(action
, callbacks
);
44 var uuid
= WCF
.getUUID();
45 callbacks
.set(uuid
, callback
);
51 * Fires an event and notifies all listeners.
53 * @param {string} identifier event identifier
54 * @param {string} action action name
55 * @param {object=} data event data
57 fire: function(identifier
, action
, data
) {
60 var actions
= _listeners
.get(identifier
);
61 if (actions
!== null) {
62 var callbacks
= actions
.get(action
);
63 if (callbacks
!== null) {
64 callbacks
.forEach(function(callback
) {
72 * Removes an event listener, requires the uuid returned by add().
74 * @param {string} identifier event identifier
75 * @param {string} action action name
76 * @param {string} uuid listener uuid
78 remove: function(identifier
, action
, uuid
) {
79 var actions
= _listeners
.get(identifier
);
80 if (actions
=== null) {
84 var callbacks
= actions
.get(action
);
85 if (callbacks
=== null) {
89 callbacks
.remove(uuid
);
93 * Removes all event listeners for given action. Omitting the second parameter will
94 * remove all listeners for this identifier.
96 * @param {string} identifier event identifier
97 * @param {string=} action action name
99 removeAll: function(identifier
, action
) {
100 var actions
= _listeners
.get(identifier
);
101 if (actions
=== null) {
105 if (typeof action
=== 'undefined') {
106 _listeners
.remove(identifier
);
109 actions
.remove(action
);
114 return new EventHandler();