Events API: подписка на события редактора
Подписка и управление событиями жизненного цикла редактора.
Как получить экземпляр редактора
Методы ниже вызываются на редакторе, созданном через new Blok(). Они доступны после того, как разрешится editor.isReady.
// You already hold the instance returned by the constructor.
const editor = new Blok({ holder: 'editor' });
await editor.isReady;
// Call any API method on it.
editor.caret.setToLastBlock('end');Методы
on(event, callback)
voidПодписаться на событие редактора.
Когда использовать
Подписка на события жизненного цикла и контента редактора. Сохраните ту же ссылку на колбэк, чтобы потом вызвать off().
// Listen for block mutations — the callback receives the event payload,
// not an API object
editor.on('block changed', ({ event }) => {
console.log('Block mutated:', event.type);
});
// Listen for individual block renders
editor.on('block:rendered', ({ blockId }) => {
console.log('Rendered block:', blockId);
});
// Wait for a container block's child holders to settle before touching them.
// A React/Vue/Angular block renders through a portal that commits AFTER
// block:rendered, so a caret set in that window is dropped; this event fires
// once the holders are in the container's slot (it repeats on every later
// reconciliation pass — it is a settle signal, not a change signal).
const child = editor.blocks.insertInsideParent(containerId);
editor.on('block:childrenMounted', ({ blockId, childIds }) => {
if (blockId === containerId && childIds.includes(child.id)) {
editor.caret.setToBlock(child.id);
}
});
// With the `collaboration` config on, this is the sync/presence indicator
// feed: status is 'connecting' | 'connected' | 'offline' | 'error', and
// participants lists everyone in the document, the reader included. 'offline'
// is still retrying (retryInMs says when) and local edits stay pending;
// 'error' has stopped for good and carries the reason. Single-player editors
// never emit it.
editor.on('collaboration:status', ({ status, participants }) => {
console.log(status, participants.map((person) => person.user.name));
});
// To react to content changes with access to the API, use the
// onChange(api, event) config callback (async is allowed there):
// onChange: async (api) => { const data = await api.save(); }off(event, callback)
voidОтписаться от события редактора.
Когда использовать
Передавайте ту же ссылку на функцию, с которой подписывались. Анонимные строчные колбэки удалить нельзя.
const handleRendered = (payload) => console.log('Rendered');
editor.on('block:rendered', handleRendered);
// Later, remove the listener (pass the same function reference)
editor.off('block:rendered', handleRendered);emit(event, data)
voidОтправить собственное событие. Это отправка без ожидания результата слушателям, зарегистрированным на этот момент. Повтора нет, поэтому обработчик, подписавшийся после отправки, никогда его не увидит.
Когда использовать
Используйте в инструментах и плагинах, чтобы рассылать свои события по шине редактора. Код приложения обычно слушает через on(), а не отправляет события.
// Subscribe first — an emit with no listener is simply dropped
editor.on('custom-event', (data) => {
console.log(data.message); // 'Hello'
});
editor.emit('custom-event', { message: 'Hello', data: 123 });