This repository has been archived by the owner on May 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEventDispatcher.js
96 lines (84 loc) · 2.33 KB
/
EventDispatcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* Broadcasts events to registered event listeners.
* @constructor
* @class
*/
EventDispatcher = function () {
this._listeners = {};
};
/**
* Register an event callback for a certain type.
* @param {String} type - The event type
* @param {Function} method - Callback if event is raised
*/
EventDispatcher.prototype.addEventListener = function (type, method) {
this._listeners[type] = this._listeners[type] || [];
this._listeners[type].push(method);
};
/**
* Sends given event to all registered event listeners for that event type
* @param {Event} event - The event
*/
EventDispatcher.prototype.dispatchEvent = function (event) {
var type = event.getType();
if (!this.hasEventListener(type)){
return;
}
event.setSender(this);
var methods = this._listeners[type];
var i = -1, l = methods.length;
while (++i < l) {
methods[i](event);
if(event._stopPropagation){
break;
}
}
};
/**
* Remove a callback from the dispatcher.
* @param {String} type = The type
* @param {Function} [method] - The callback to be removed (if not specified, all callbacks will be removed)
*/
EventDispatcher.prototype.removeEventListener = function (type, method) {
if (!this.hasEventListener(type)){
return;
}
if(method){
var methods = this._listeners[type];
var i = methods.length;
while (--i > -1) {
if (methods[i] == method) {
methods.splice(i, 1);
if (methods.length == 0){
delete this._listeners[type];
}
break;
}
}
return;
}
delete this._listeners[type];
};
/**
* Completely remove all listeners.
*/
EventDispatcher.prototype.removeAllEventListeners = function () {
this._listeners = {};
};
/**
* Returns true there are listeners for a event type.
* @param {String} type - The type
* @returns {Boolean}
*/
EventDispatcher.prototype.hasEventListener = function (type) {
return this._listeners[type] != undefined && this._listeners[type] != null;
};
///**
// * Returns the number of listerners for a certain event type.
// * @returns {*}
// */
//
//EventDispatcher.prototype.getNumListerners = function(){
// return ObjectUtil.getNumKeys(this._listeners);
//}
module.exports = EventDispatcher;