forked from chrisdavies/eev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eev.js
89 lines (71 loc) · 2.01 KB
/
eev.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
var Eev = (function () {
var id = 0;
var splitter = /[^\w\-]+/g;
// A relatively generic LinkedList impl
function LinkedList(linkConstructor) {
this.head = new RunnableLink();
this.tail = new RunnableLink(this.head);
this.head.next = this.tail;
this.linkConstructor = linkConstructor;
this.reg = {};
}
LinkedList.prototype = {
insert: function (data) {
var link = new RunnableLink(this.tail.prev, this.tail, data);
link.next.prev = link.prev.next = link;
return link;
},
remove: function (link) {
link.prev.next = link.next;
link.next.prev = link.prev;
}
};
// A link in the linked list which allows
// for efficient execution of the callbacks
function RunnableLink(prev, next, fn) {
this.prev = prev;
this.next = next;
this.fn = fn || noop;
}
RunnableLink.prototype.run = function (data) {
this.fn(data);
this.next && this.next.run(data);
};
function noop () { }
function Eev () {
this.events = {};
}
Eev.prototype = {
on: function (names, fn) {
var me = this;
names.split(splitter).forEach(function (name) {
var list = me.events[name] || (me.events[name] = new LinkedList());
var eev = fn._eev || (fn._eev = (++id));
list.reg[eev] || (list.reg[eev] = list.insert(fn));
});
},
off: function (names, fn) {
var me = this;
names.split(splitter).forEach(function (name) {
var list = me.events[name];
var link = list.reg[fn._eev];
list.reg[fn._eev] = undefined;
list && link && list.remove(link);
});
},
emit: function (name, data) {
var evt = this.events[name];
evt && evt.head.run(data);
}
};
return Eev;
}());
// AMD/CommonJS support
(function (root, factory) {
var define = root.define;
if (define && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
}
}(this, function () { return Eev; }));