-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventize.js
51 lines (51 loc) · 1.29 KB
/
eventize.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
(function () {
var callbacksProperty = "__eventCallbacks__";
var isArray = function (array) {
return array instanceof Array
};
var trigger = function (event) {
if (!this.hasOwnProperty(callbacksProperty)) {
return
}
var callbacks = this[callbacksProperty][event];
if (!isArray(callbacks)) {
return
}
var args = [].slice.call(arguments, 1);
for (var i = 0; i < callbacks.length; i++) {
if (typeof callbacks[i] === "function") {
callbacks[i].apply(this, args)
}
}
};
var on = function (event, callback) {
if (!this.hasOwnProperty(callbacksProperty)) {
return
}
var callbacks = this[callbacksProperty][event];
if (!isArray(callbacks)) {
callbacks = this[callbacksProperty][event] = []
}
callbacks.push(callback)
};
var off = function (event, callback) {
if (!this.hasOwnProperty(callbacksProperty)) {
return
}
var callbacks = this[callbacksProperty][event];
if (!isArray(callbacks)) {
return
}
for (var i = callbacks.length; i-- > 0;) {
if (callbacks[i] === callback) {
callbacks.splice(i, 1)
}
}
};
module.exports = function (obj) {
obj[callbacksProperty] = {};
obj.trigger = trigger;
obj.on = on;
obj.off = off
}
})();