-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
52 lines (39 loc) · 1.11 KB
/
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
(function(exports, module, self) {
var Events = {};
Events.extend = function(obj) {
obj.on = this.on;
obj.off = this.off;
obj.trigger = this.trigger;
};
function fetchCallbacks(promise, evt) {
if ( !promise.eventMap ) promise.eventMap = {};
if ( !promise.eventMap[evt] ) promise.eventMap[evt] = [];
return promise.eventMap[evt];
}
Events.on = function(evt, cb) {
var callbacks = fetchCallbacks(this, evt);
callbacks.push(cb);
return this;
};
Events.off = function(evt) {
if ( this.eventMap && this.eventMap[evt] )
delete this.eventMap[evt];
return this;
};
Events.trigger = function(evt, args) {
if ( !this.eventMap ) this.eventMap = {};
var callbacks = this.eventMap[evt] || [],
_this = this;
each(callbacks, function(callback, index) {
callback.apply(_this, [args]);
});
};
function each(lst, fn) {
for ( var i = 0, len = lst.length; i < len; i++ )
fn(lst[i], i);
}
if ( typeof exports !== "undefined" )
exports = module.exports = Events;
else
this.Events = Events;
})(exports, module, this);