-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
81 lines (68 loc) · 2.06 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
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
/*********************************
* @author: Trung Trung Kang <[email protected]>
* @data: 12/26/15
*
* Events pattern
*****************************************************/
function Events(){}
Events.prototype = (function(){
var events = {};
function getNames(name){
var kv = {tag: null};
var names = name.split(':');
if(names.length > 1) {
kv.tag = names[0];
kv.name = names[1];
}
else kv.name = name;
return kv;
}
function raiseEvent(name, args, ctx){
var evts = events[name];
if(evts){
for(var i = 0; i < evts.length;){
var h = evts[i];
if(h.once) evts.splice(i, 1);
else i++;
var fn = h.fn;
fn.apply(ctx, args || []);
}
}
}
return {
emit: function(name, ctx){
this.raise(name, [].slice.call(arguments, 1), ctx);
},
raise: function(name, args, ctx){
raiseEvent(name, args, ctx);
},
once: function(name, fn){
this.on(name, fn, true);
return this;
},
on: function(name, fn, once){
var kv = getNames(name);
var _name = kv.name;
var evts = events[_name];
if(!evts) evts = events[_name] = [];
evts.push({fn: fn, once: once, tag: kv.tag});
return this;
},
off: function(name, fn){
var kv = getNames(name);
var _name = kv.name;
var _tag = kv.tag;
var no_tag = (name.indexOf(':') === -1);
var evts = events[_name];
if(evts){
for(var i = 0; i < evts.length; i++){
var h = evts[i];
if((fn && h.fn === fn) || no_tag || h.tag === _tag)
evts.splice(i, 1);
}
}
return this;
}
};
})();
module.exports = Events;