-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-manager.js
89 lines (72 loc) · 2.6 KB
/
event-manager.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
(function () {
function EventManager() {
this.events = {};
};
EventManager.prototype.on = EventManager.prototype.addEventListener = function addEventlistener(event, fn) {
if (typeof fn !== "function")
throw new TypeError("The listener must be a function");
if (!this.events[event]) {
this.events[event] = [];
}
if (!this[event])
this[event] = this.trigger.bind(this, event);
this.events[event].push(fn);
};
EventManager.prototype.off = EventManager.prototype.removeAllEventListener = function removeAllEventListener(event) {
this.events[event] = [];
};
EventManager.prototype.removeEventListener = function removeEventListener(event, fn) {
if (!this.events[event])
return;
var index = this.events[event].indexOf(fn);
if (index == -1)
return;
this.events[event].splice(index, 1);
};
EventManager.prototype.trigger = EventManager.prototype.emmit = function trigger(event) {
var self = this,
args = Array.prototype.slice.call(arguments, 1);
if (!this.events[event])
return;
if (this.async) {
setTimeout(function () {
self.events[event].forEach(function (e) {
e.apply(self.target, args);
});
}, 0);
} else {
this.events[event].forEach(function (e) {
e.apply(self.target, args);
});
}
};
EventManager.prototype.once = function once(event, fn) {
var self = this,
args = arguments,
toReg = function toReg() {
fn.apply(self.target, arguments);
self.removeEventListener(event, toReg);
};
this.on(event, toReg);
};
EventManager.makeEmmitter = function makeEmmitter(object) {
object.eventManager = new EventManager();
for (var prop in object.eventManager) {
if (typeof object.eventManager[prop] === "function") {
object[prop] = object.eventManager[prop].bind(object.eventManager);
}
}
}
if (typeof define === 'function' && define.amd) {
define('event-manager', [], function () {
return EventManager;
});
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = EventManager;
}
exports.eventManager = EventManager;
} else {
window.EventManager = EventManager;
}
}());