-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathofio.events.js
94 lines (68 loc) · 2.15 KB
/
ofio.events.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
define(['ofio/ofio'], function (Ofio) {
var listeners_by_id = {};
var id = 0;
var class_on = function (event, listener) {
var listeners;
if (!this.listeners[event])
listeners = this.listeners[event] = {};
else
listeners = this.listeners[event];
listeners[id] = listener;
listeners_by_id[id] = listeners;
return id++;
};
//todo: parents
var class_emit = function (event) {
var listeners = this.listeners[ event ];
if (!listeners) return;
var args = Array.prototype.slice.call(arguments, 1);
for (var id in listeners) {
listeners[ id ].apply(this, args);
}
};
var on_include = function (clazz) {
clazz.listeners = {};
clazz.on = class_on;
clazz.emit = class_emit;
};
//todo: remove listener for classes
var module = new Ofio.Module({
name: 'ofio.events',
onInclude: on_include
});
module.init = function () {
this.__listeners = {};
};
module.on = function (event, listener) {
var listeners;
if (typeof listener != "function")
throw new Error('Second argument must be a function');
if (!this.__listeners[event])
listeners = this.__listeners[event] = {};
else
listeners = this.__listeners[event];
listeners[ id ] = listener;
listeners_by_id[ id ] = listeners;
return id++;
};
module.emit = function (event) {
var args = Array.prototype.slice.call(arguments, 1);
var listeners = this.__listeners[event];
for (var id in listeners) {
listeners[id].apply(this, args);
}
args.unshift(event, this);
var parent = this;
while (parent) {
if (!parent.emit) break;
parent.constructor.emit.apply(parent.constructor, args);
parent = parent.parent;
}
};
module.remove_listener = function (id) {
var listeners = listeners_by_id[ id ];
if (!listeners) return false;
delete listeners[ id ];
};
return module;
});