2018-08-13 15:49:39 +08:00
|
|
|
const log = require('./log');
|
|
|
|
|
2018-08-01 15:26:02 +08:00
|
|
|
const NOTE_TITLE_CHANGED = "NOTE_TITLE_CHANGED";
|
2018-04-20 12:12:01 +08:00
|
|
|
const ENTER_PROTECTED_SESSION = "ENTER_PROTECTED_SESSION";
|
2018-08-16 04:06:49 +08:00
|
|
|
const ENTITY_CREATED = "ENTITY_CREATED";
|
2018-04-20 12:12:01 +08:00
|
|
|
const ENTITY_CHANGED = "ENTITY_CHANGED";
|
2018-11-13 06:34:22 +08:00
|
|
|
const ENTITY_DELETED = "ENTITY_DELETED";
|
2019-01-04 06:27:10 +08:00
|
|
|
const ENTITY_SYNCED = "ENTITY_SYNCED";
|
2018-08-16 04:06:49 +08:00
|
|
|
const CHILD_NOTE_CREATED = "CHILD_NOTE_CREATED";
|
2018-04-20 12:12:01 +08:00
|
|
|
|
|
|
|
const eventListeners = {};
|
|
|
|
|
2019-01-04 06:27:10 +08:00
|
|
|
/**
|
|
|
|
* @param eventTypes - can be either single event or an array of events
|
|
|
|
* @param listener
|
|
|
|
*/
|
|
|
|
function subscribe(eventTypes, listener) {
|
|
|
|
if (!Array.isArray(eventTypes)) {
|
|
|
|
eventTypes = [ eventTypes ];
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const eventType of eventTypes) {
|
|
|
|
eventListeners[eventType] = eventListeners[eventType] || [];
|
|
|
|
eventListeners[eventType].push(listener);
|
|
|
|
}
|
2018-04-20 12:12:01 +08:00
|
|
|
}
|
|
|
|
|
2018-08-13 02:07:02 +08:00
|
|
|
async function emit(eventType, data) {
|
2018-08-01 15:26:02 +08:00
|
|
|
const listeners = eventListeners[eventType];
|
|
|
|
|
|
|
|
if (listeners) {
|
|
|
|
for (const listener of listeners) {
|
2018-08-13 15:49:39 +08:00
|
|
|
try {
|
|
|
|
await listener(data);
|
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
log.error("Listener threw error: " + e.stack);
|
|
|
|
// we won't stop execution because of listener
|
|
|
|
}
|
2018-08-01 15:26:02 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-20 12:12:01 +08:00
|
|
|
module.exports = {
|
|
|
|
subscribe,
|
|
|
|
emit,
|
|
|
|
// event types:
|
2018-08-01 15:26:02 +08:00
|
|
|
NOTE_TITLE_CHANGED,
|
2018-04-20 12:12:01 +08:00
|
|
|
ENTER_PROTECTED_SESSION,
|
2018-08-16 04:06:49 +08:00
|
|
|
ENTITY_CREATED,
|
|
|
|
ENTITY_CHANGED,
|
2018-11-13 06:34:22 +08:00
|
|
|
ENTITY_DELETED,
|
2019-01-04 06:27:10 +08:00
|
|
|
ENTITY_SYNCED,
|
2018-08-16 04:06:49 +08:00
|
|
|
CHILD_NOTE_CREATED
|
2018-04-20 12:12:01 +08:00
|
|
|
};
|