Repository navigation
Expand file tree
/
Copy pathswitchboard.js
More file actions
79 lines (71 loc) · 2.21 KB
/
Copy pathswitchboard.js
File metadata and controls
79 lines (71 loc) · 2.21 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import {Emitter} from 'event-kit';
/*
* Register callbacks and construct Promises to wait for the next occurrence of specific events that occur throughout
* the data refresh and rendering cycle.
*/
export default class Switchboard {
constructor() {
this.promises = new Map();
this.emitter = new Emitter();
}
/*
* Invoke a callback each time that a desired event is observed. Return a Disposable that can be used to
* unsubscribe from events.
*
* In general, you should use the more specific `onDidXyz` methods.
*/
onDid(eventName, callback) {
return this.emitter.on(`did-${eventName}`, callback);
}
/*
* Indicate that a named event has been observed, firing any callbacks and resolving any Promises that were created
* for this event. Optionally provide a payload with more information.
*
* In general, you should prefer the more specific `didXyz()` methods.
*/
did(eventName, payload) {
this.emitter.emit(`did-${eventName}`, payload);
}
/*
* Retrieve a Promise that will be resolved the next time a desired event is observed.
*
* In general, you should prefer the more specific `getXyzPromise()` methods.
*/
getPromise(eventName) {
const existing = this.promises.get(eventName);
if (existing !== undefined) {
return existing;
}
const created = new Promise((resolve, reject) => {
const subscription = this.onDid(eventName, payload => {
subscription.dispose();
this.promises.delete(eventName);
resolve(payload);
});
});
this.promises.set(eventName, created);
return created;
}
}
[
'UpdateRepository',
'BeginStageOperation',
'FinishStageOperation',
'ChangePatch',
'ScheduleActiveContextUpdate',
'BeginActiveContextUpdate',
'FinishActiveContextUpdate',
'FinishRender',
'FinishContextChangeRender',
'FinishRepositoryRefresh',
].forEach(eventName => {
Switchboard.prototype[`did${eventName}`] = function(payload) {
this.did(eventName, payload);
};
Switchboard.prototype[`get${eventName}Promise`] = function() {
return this.getPromise(eventName);
};
Switchboard.prototype[`onDid${eventName}`] = function(callback) {
return this.onDid(eventName, callback);
};
});