Skip to content
ФреймворкJavaScript

Events API: подписка на события редактора

Подписка и управление событиями жизненного цикла редактора.

Как получить экземпляр редактора

Методы ниже вызываются на редакторе, созданном через new Blok(). Они доступны после того, как разрешится editor.isReady.

TypeScript
// 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

Subscribe to an editor event.

Когда использовать

Подписка на события жизненного цикла/контента редактора. Сохраните ту же ссылку на колбэк, чтобы потом вызвать off().

TypeScript
// 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);
  }
});

// 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

Unsubscribe from an editor event.

Когда использовать

Передавайте ту же ссылку на функцию, с которой подписывались — анонимные инлайн-колбэки удалить нельзя.

TypeScript
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

Emit a custom event. Fire-and-forget over the listeners registered at that moment — there is no replay, so a handler subscribed after the emit never sees it.

Когда использовать

Для инструментов/плагинов, рассылающих свои события по шине редактора; код приложения обычно слушает через on(), а не эмитит.

TypeScript
// 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 });