-
Notifications
You must be signed in to change notification settings - Fork 0
/
tj.js
114 lines (87 loc) · 3.14 KB
/
tj.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
(function (tj, global) {
'use strict';
var numTokensRequested = 0;
var is = require('is-simple');
var allSubscribers = {}; // event -> {token: <string>, fn: <Function>}
var getUniqueToken = (function () {
numTokensRequested += 1;
return String(numTokensRequested);
});
var emit = (function (event, args) {
if (allSubscribers.hasOwnProperty(event)) {
var eventSubscribers = allSubscribers[event];
for (var i = 0; i < eventSubscribers.length; i++) {
var fn = eventSubscribers[i].fn;
try {
fn.apply(global, args)
} catch (e) {
setTimeout(function () {
throw e;
}, 0);
}
}
}
});
var checkArgs = (function (event, args) {
if (allSubscribers.hasOwnProperty(event)) {
var eventSubscribers = allSubscribers[event];
var valid = true;
for (var i = 0; i < eventSubscribers.length && valid; i++) {
var signature = eventSubscribers[i].signature;
valid = signature.length === args.length;
for (var j = 0; j < signature.length && valid; j++) {
valid = signature[j](args[j]);
}
}
if (!valid) {
throw new Error('Invalid args for event ' + event);
}
}
});
tj.clearAllSubscriptions = (function () {
allSubscribers = {};
});
tj.publish = (function (event) {
var args = [].slice.call(arguments, 1, arguments.length);
checkArgs(event, args);
setTimeout(function () {
emit(event, args);
}, 0);
});
tj.publishSync = (function (event) {
var args = [].slice.call(arguments, 1, arguments.length);
checkArgs(event, args);
emit(event, args);
});
tj.subscribe = (function (event) {
var token = getUniqueToken();
var fn = arguments[arguments.length - 1];
var signature = [].slice.call(arguments, 1, arguments.length - 1);
if (!allSubscribers.hasOwnProperty(event)) {
// this is the first subscriber to this event
allSubscribers[event] = [];
}
allSubscribers[event].push({
token: token,
signature: signature,
fn: fn
});
return token;
});
tj.unsubscribe = (function (token) {
var event;
for (event in allSubscribers) {
if (allSubscribers.hasOwnProperty(event)) {
var eventSubscribers = allSubscribers[event];
for (var i = 0; i < eventSubscribers.length; i++) {
var eventSubscriber = eventSubscribers[i];
if (eventSubscriber.token === token) {
eventSubscribers.splice(i, 1); // remove the subscriber
return true; // nothing else to do
}
}
}
}
return false;
});
}(typeof exports === 'undefined' ? this.tj = {} : exports, this));