/
EventTarget.js
91 lines (77 loc) · 2.41 KB
/
EventTarget.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
"use strict";
module.exports = EventTarget;
/**
* A generic base to inherit from for any object
* that needs event handling.
* @class EventTarget
* @constructor
*/
function EventTarget() {
/**
* The array of listeners for various events.
* @type Object
* @property _listeners
* @private
*/
this._listeners = Object.create(null);
}
EventTarget.prototype = {
// restore constructor
constructor: EventTarget,
/**
* Adds a listener for a given event type.
* @param {String} type The type of event to add a listener for.
* @param {Function} listener The function to call when the event occurs.
* @return {void}
* @method addListener
*/
addListener: function(type, listener) {
if (!this._listeners[type]) {
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
/**
* Fires an event based on the passed-in object.
* @param {Object|String} event An object with at least a 'type' attribute
* or a string indicating the event name.
* @return {void}
* @method fire
*/
fire: function(event) {
if (typeof event === "string") {
event = { type: event };
}
if (typeof event.target !== "undefined") {
event.target = this;
}
if (typeof event.type === "undefined") {
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type]) {
// create a copy of the array and use that so listeners can't chane
var listeners = this._listeners[event.type].concat();
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i].call(this, event);
}
}
},
/**
* Removes a listener for a given event type.
* @param {String} type The type of event to remove a listener from.
* @param {Function} listener The function to remove from the event.
* @return {void}
* @method removeListener
*/
removeListener: function(type, listener) {
if (this._listeners[type]) {
var listeners = this._listeners[type];
for (var i = 0, len = listeners.length; i < len; i++) {
if (listeners[i] === listener) {
listeners.splice(i, 1);
break;
}
}
}
}
};