1. Spreadsheet docs
  2. Developers

Events

Listen to cell changes, selection, editing, clipboard, sheets and calculation, and stop actions with cancellable before- events.

Events tell your code what happens in a workbook: cells that changed, a new selection, an editor opening, a sheet about to be deleted, calculation finishing. Events named before-… come before the action and can stop it, and a few let you change what is about to happen, such as the text a user is about to enter.

Edits fire the same events whichever way they happen: typing, paste, fill, undo and redo, and writes from your own code.

Listen and stop listening

JavaScript

import { mountWorkbook } from '@8sheets/core';

const wb = await mountWorkbook(document.querySelector('#sheet'));

// Every changed cell, from any source.
const off = wb.events.on('cells-changed', (e) => {
  for (const { row, col } of e.cells()) {
    console.log(e.sheet.name, row, col, e.sheet.cell(row, col).values[0][0], e.reason);
  }
});

// Upper-case product codes as they are entered.
wb.events.on('before-commit', (e) => {
  if (e.col === 0) e.text = e.text.toUpperCase();
});

// Ask before a sheet is deleted.
wb.events.on('before-sheet-remove', (e) => {
  if (!confirm(`Delete the sheet ${e.sheet.name}?`)) e.cancel();
});

off();   // stop listening

React

import { Sheet } from '@8sheets/react';

export function Products() {
  return (
    <div style={{ height: 480 }}>
      <Sheet
        onCellsChanged={(e) => {
          for (const { row, col } of e.cells()) {
            console.log(e.sheet.name, row, col, e.sheet.cell(row, col).values[0][0], e.reason);
          }
        }}
        onBeforeCommit={(e) => { if (e.col === 0) e.text = e.text.toUpperCase(); }}
        onBeforeSheetRemove={(e) => { if (!confirm(`Delete the sheet ${e.sheet.name}?`)) e.cancel(); }}
      />
    </div>
  );
}

Vue

<script setup>
import { Sheet } from '@8sheets/vue';

function logCells(e) {
  for (const { row, col } of e.cells()) {
    console.log(e.sheet.name, row, col, e.sheet.cell(row, col).values[0][0], e.reason);
  }
}
function upperCodes(e) {
  if (e.col === 0) e.text = e.text.toUpperCase();
}
function confirmRemove(e) {
  if (!confirm(`Delete the sheet ${e.sheet.name}?`)) e.cancel();
}
</script>

<template>
  <Sheet
    style="height: 480px"
    @cells-changed="logCells"
    @before-commit="upperCodes"
    @before-sheet-remove="confirmRemove"
  />
</template>

Angular

import { Component } from '@angular/core';
import { SheetComponent, SheetEventPayload } from '@8sheets/angular';

@Component({
  selector: 'app-products',
  imports: [SheetComponent],
  template: `
    <eight-sheet class="grid"
      (cellsChanged)="logCells($event)"
      (beforeCommit)="upperCodes($event)"
      (beforeSheetRemove)="confirmRemove($event)" />
  `,
  styles: `.grid { height: 480px; }`,
})
export class Products {
  logCells(e: SheetEventPayload) {
    for (const { row, col } of e['cells']()) {
      console.log(e['sheet'].name, row, col, e['sheet'].cell(row, col).values[0][0], e['reason']);
    }
  }

  upperCodes(e: SheetEventPayload) {
    if (e['col'] === 0) e['text'] = e['text'].toUpperCase();
  }

  confirmRemove(e: SheetEventPayload) {
    if (!confirm(`Delete the sheet ${e['sheet'].name}?`)) e.cancel();
  }
}

wb.events.on(type, fn, options) returns a function that removes the listener; wb.events.off(type, fn) does the same, and off(type) removes every listener of a type. Options: once: true removes the listener after its first call, and signal removes it when an AbortSignal fires, which suits code that already uses an AbortController.

In the components, each event is a prop, listener or output (see React, Vue and Angular), and the component removes its listeners when it unmounts.

The event object

Every event object has:

  • type: the event name,
  • workbook: the workbook it came from,
  • cancelled and cancel(): for before-… events, cancel() stops the action,
  • the fields of that event, such as sheet, row, col, text or from and to.

Some events let you change what happens, not only stop it:

EventWhat you can change
before-commitSet e.text to store other text than the user typed. Cancelling keeps the editor open.
before-zoomSet e.zoom to clamp the zoom, or cancel.
menu-openingEdit e.items in place to change the context menu.
range-sortingSet e.info.compareFunction to compare two cell values your own way.

The events you will use most

EventFieldsWhen
cells-changedsheet, label, reason, count, bounds, cells()Cells changed through any path. reason is edit, undo or redo; label names the step, such as entry (typed text, and formulas written from code) or set-values (range.values from code); bounds is the changed box { r0, c0, r1, c1 }; cells() lists { row, col } lazily.
step-donesheet, label, reasonAny undo step, including ones that touch no cell, such as a format or a theme. Use it to mark a document dirty.
selection-changedsheet, from, toThe selection changed. to is { ranges, row, col }, with ranges as zero-based boxes; wb.selectedRanges gives them as ranges with an address.
cell-click, cell-double-clicksheet, hit, originalEventA click on a cell or header. hit says what was hit, such as { area: 'grid', element: 'cell', row, col }.
before-editsheet, row, col, initial, originA cell editor is about to open. Cancel to keep a cell from being edited.
before-commitsheet, row, col, textThe editor is about to store its text.
validation-failedsheet, row, col, text, ruleEntered text breaks the cell's data validation rule.
before-changelabel, sheetAny undoable edit is about to run, from the user or from code. Cancel to refuse it.
before-command, after-commandname, args, source (and result after)Any command is about to run, and after it ran: run by your code (source: 'api'), or a built-in ribbon control, menu row or key the user used (ribbon, menu, key). before-command is cancellable; for api it can change args. command-executed fires only for commands your code runs. See Control everything from code.
before-paste, after-pastesheet, ranges, textPaste; text is the plain text on the clipboard.
active-sheet-changedfrom, toAnother sheet is shown.
before-sheet-remove, before-sheet-rename, before-sheet-movesheet, and from, toSheet management, cancellable.
calc-endCalculation finished and all values are current.
workbook-loadedsourcefromJSON or openDocument replaced the contents.
invalid-operationaction, reasonAn action was refused, by protection or by a listener.

The API reference lists all 66 events with their fields, which can be cancelled, and which need a mounted workbook.

Events need a page, or not

Events about the model (cells, structure, sheets, calculation, comments, theme) fire in a headless workbook too, so the same listener code runs in Node. Events about the screen (selection, pointer, editing, clipboard, zoom, scrolling, menus) need a mounted workbook.

Patterns

Keep a list of changed cells to save

Collect what changed and send it in batches rather than on every keystroke:

const dirty = new Map();   // "sheet!row:col" -> { sheet, row, col }
wb.events.on('cells-changed', (e) => {
  for (const { row, col } of e.cells()) dirty.set(`${e.sheet.name}!${row}:${col}`, { sheet: e.sheet.name, row, col });
  scheduleSave();
});

let timer = 0;
function scheduleSave() {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const changes = [...dirty.values()].map(({ sheet, row, col }) => ({
      sheet, row, col, value: wb.sheet(sheet).cell(row, col).values[0][0],
    }));
    dirty.clear();
    await fetch('/api/cells', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(changes) });
  }, 1000);
}

A paste or a bulk write can change many cells at once; e.count and e.bounds tell you how many before you list them.

Validate input before it lands

wb.events.on('before-commit', (e) => {
  if (e.sheet.name === 'Orders' && e.col === 3 && !/^\d+$/.test(e.text)) {
    e.cancel();   // the editor stays open with the text
    wb.statusBar.setMessage('Units must be a whole number.');
  }
});

For rules that should travel with the file and show Excel's own input messages and alerts, use data validation instead.

Follow the selection

wb.events.on('selection-changed', (e) => {
  const { row, col } = e.to;
  const value = e.sheet.cell(row, col).values[0][0];
  document.querySelector('#details').textContent = `${wb.selectedRanges.map((r) => r.address).join(', ')}: ${value ?? ''}`;
});

Ignore your own writes

Writes from your code fire cells-changed too. The label doesn't tell them apart reliably (range.formulas is labelled entry, as typing is), so mark your own writes with a flag:

let applyingServerUpdate = false;

function applyFromServer(sheetName, address, rows) {
  applyingServerUpdate = true;
  try {
    wb.sheet(sheetName).range(address).values = rows;
  } finally {
    applyingServerUpdate = false;
  }
}

wb.events.on('cells-changed', (e) => {
  if (applyingServerUpdate) return;   // our own update, already on the server
  queueForServer(e);
});

Listeners run synchronously during the write, so the flag is set while they run.

Cost

A workbook installs the hooks for a group of events only while that group has at least one listener. With none, the app runs its own methods with nothing in between, so an event you don't listen to costs nothing. Keep listeners on frequent events (scrolled, edit-input, cell-enter) light, and remove them when you no longer need them.