forked from LRH1993/android_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemit.js
More file actions
61 lines (54 loc) · 1.76 KB
/
emit.js
File metadata and controls
61 lines (54 loc) · 1.76 KB
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
var test = require('tape');
var EventEmitter = require('events').EventEmitter;
var dnode = require('../');
test('emit events', function (t) {
t.plan(1);
var subs = [];
function publish (name) {
var args = [].slice.call(arguments, 1);
for (var i = 0; i < subs.length; i++) {
subs[i].emit(name, args);
}
}
var server = function () {
return dnode(function (remote, conn) {
this.subscribe = function (emit) {
subs.push({ emit : emit, id : conn.id });
conn.on('end', function () {
for (var i = 0; i < subs.length; i++) {
if (subs.id === conn.id) {
subs.splice(i, 1);
break;
}
}
});
};
});
};
setTimeout(function () {
var times = 0;
var iv = setInterval(function () {
if (++times === 5) {
t.deepEqual(xs, ys);
return clearInterval(iv);
}
else publish('data', Math.floor(Math.random() * 100));
}, 20);
}, 20);
var xs = [];
var x = dnode();
x.on('remote', function (remote) {
var em = new EventEmitter;
em.on('data', function (n) { xs.push(n) });
remote.subscribe(function () { return em.emit.apply(em, arguments) });
});
x.pipe(server()).pipe(x);
var ys = [];
var y = dnode();
y.on('remote', function (remote) {
var em = new EventEmitter;
em.on('data', function (n) { ys.push(n) });
remote.subscribe(function () { return em.emit.apply(em, arguments) });
});
y.pipe(server()).pipe(y);
});