trilium/src/services/events.js

55 lines
1.4 KiB
JavaScript
Raw Normal View History

const log = require('./log');
const NOTE_TITLE_CHANGED = "NOTE_TITLE_CHANGED";
const ENTER_PROTECTED_SESSION = "ENTER_PROTECTED_SESSION";
const ENTITY_CREATED = "ENTITY_CREATED";
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";
const CHILD_NOTE_CREATED = "CHILD_NOTE_CREATED";
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-08-13 02:07:02 +08:00
async function emit(eventType, data) {
const listeners = eventListeners[eventType];
if (listeners) {
for (const listener of listeners) {
try {
await listener(data);
}
catch (e) {
log.error("Listener threw error: " + e.stack);
// we won't stop execution because of listener
}
}
}
}
module.exports = {
subscribe,
emit,
// event types:
NOTE_TITLE_CHANGED,
ENTER_PROTECTED_SESSION,
ENTITY_CREATED,
ENTITY_CHANGED,
2018-11-13 06:34:22 +08:00
ENTITY_DELETED,
2019-01-04 06:27:10 +08:00
ENTITY_SYNCED,
CHILD_NOTE_CREATED
};