# Events reference

> Every event the grid emits, with its payload and a typical use, plus how to subscribe and unsubscribe.

Subscribe with `api.on(event, listener)`. It returns a function that removes the listener. Every payload is a single object, typed from `GridEvents<TRow>`, so `row` is your row type without casts.

```ts title="events.ts"
import { createGrid } from '@birchui/core';

const grid = createGrid<Order>(document.querySelector('#orders')!, { columns, rows: orders, getRowId: (o) => o.id });

const off = grid.on('cellClick', ({ row, colId, value }) => {
  console.info(`${row?.id} ${colId}: ${String(value)}`);
});

off();
```

Listeners are also released when you call `grid.destroy()`. Framework adapters expose the same events as props or outputs, for example `onCellClick` in React, `@cell-click` in Vue and the `cell-click` DOM event on `<birchui-grid>`. See [Frameworks](https://docs.birchui.com/frameworks/react.md).

> **Note**
>
> Listeners run synchronously while the grid processes a change. If a listener throws, the grid catches the error and reports it with `console.error` (`Birch UI: a "cellClick" listener threw`), then carries on: other listeners for the same event still run and the grid's own state is unaffected. Catch errors yourself when you want to show them to users.

## Lifecycle

### ready

`{ api }`. Fires once, in a microtask after `createGrid()` returns and the first render is done, so a listener attached right after creation still receives it. Use it in framework adapters where the API object arrives asynchronously.

```ts
grid.on('ready', ({ api }) => api.autosizeColumns());
```

### modelUpdated

`{ rowCount, displayRowCount }`. Fires after every run of the row pipeline: new rows, transactions, option updates, sort, filter, paging, expansion and grouping changes. `rowCount` is the number of source rows; `displayRowCount` is the number of display rows across all pages.

```ts
grid.on('modelUpdated', ({ rowCount, displayRowCount }) => {
  footer.textContent = `${displayRowCount.toLocaleString()} of ${rowCount.toLocaleString()} orders`;
});
```

## Cells and rows

### cellClick, cellDoubleClick

`CellEvent`: `{ row, displayRow, rowIndex, colId, value, event }`. `row` is `undefined` for rows without data, such as group rows.

```ts
grid.on('cellDoubleClick', ({ row, colId }) => {
  if (row && colId === 'customer') openCustomer(row.customerId);
});
```

### cellKeyDown

`CellEvent` with the `KeyboardEvent` in `event`. Fires for every key pressed while a body cell has focus and no editor is open, before module key handlers and the built-in key map. Call `event.preventDefault()` to cancel the grid's own handling of that key, including navigation and starting an edit.

```ts
grid.on('cellKeyDown', ({ event, row }) => {
  const key = event as KeyboardEvent;
  if (key.key === 'Delete' && row) {
    key.preventDefault();
    archiveOrder(row.id).then(() => grid.applyTransaction({ remove: [row] }));
  }
});
```

### rowClick

`{ row, displayRow, rowIndex, event }`. Fires for clicks on any cell of a row, right after `cellClick`.

```ts
grid.on('rowClick', ({ row }) => row && showPreview(row));
```

### rowExpanded

`{ rowId, expanded }`. Fires once for each row whose state changes through a click, a key or `setExpanded()`, including each ID passed in an array. `expandAll()` and `collapseAll()` do not fire it per row; listen to `modelUpdated` for those.

```ts
grid.on('rowExpanded', ({ rowId, expanded }) => analytics.track('row_toggle', { rowId, expanded }));
```

### focusChanged

`{ cell }`, where `cell` is a `CellPosition` (`{ rowIndex, colId }`, with `rowIndex: -1` for the header row) or `null`. Fires when the focused cell changes, by click, keyboard or `focusCell()`.

```ts
grid.on('focusChanged', ({ cell }) => {
  inspector.hidden = cell === null;
  if (cell) inspector.show(grid.getDisplayRow(cell.rowIndex)?.data);
});
```

### viewportScroll

`{ top, left }`, the viewport's scroll position in pixels. Fires on every scroll event, so keep listeners cheap. For grids taller than 10,000,000 pixels, `top` is the scaled scrollbar position, not the virtual offset. Adapters expose it as `onViewportScroll` in React, Svelte and Solid, `@viewport-scroll` in Vue, `(viewportScroll)` in Angular and the `viewport-scroll` DOM event on `<birchui-grid>`.

```ts
grid.on('viewportScroll', ({ left }) => toolbar.classList.toggle('is-scrolled', left > 0));
```

## Editing

### editStart, editStop

`editStart` is a `CellPosition` (`{ rowIndex, colId }`). `editStop` adds `cancelled: boolean`.

```ts
grid.on('editStart', ({ colId }) => hint.show(`Editing ${colId}. Press Enter to save, Escape to cancel.`));
grid.on('editStop', () => hint.hide());
```

### cellValueChanged

`{ row, rowIndex, colId, oldValue, newValue, source }`. Fires after a value is written, only when it changed. `source` is `'edit'`, `'api'`, `'paste'` or `'fill'`. `rowIndex` is `-1` when the row is not among the current display rows, for example when it is filtered out.

```ts
grid.on('cellValueChanged', ({ row, colId, newValue, source }) => {
  if (source !== 'api') saveQueue.push({ id: row.id, field: colId, value: newValue });
});
```

## Selection, sort and filter

### selectionChanged

`{ selected }`, the selected row objects. Fires on every selection change from clicks, keys, checkboxes and the API, and when new data or a transaction removes selected rows.

```ts
grid.on('selectionChanged', ({ selected }) => {
  bulkBar.hidden = selected.length === 0;
  bulkCount.textContent = String(selected.length);
});
```

### sortChanged

`{ sort }`, the new `SortItem[]`. Fires for header clicks and keys, the column menu, `setSort()` and `update({ sort })`.

```ts
grid.on('sortChanged', ({ sort }) => url.searchParams.set('sort', sort.map((s) => `${s.colId}:${s.dir}`).join(',')));
```

### filterChanged

`{ filterModel, quickFilter }`. Fires for floating filter input, `setFilter()`, `setFilterModel()`, `setQuickFilter()` and `update({ filterModel })` or `update({ quickFilter })`.

```ts
grid.on('filterChanged', ({ filterModel, quickFilter }) => {
  clearButton.disabled = Object.keys(filterModel).length === 0 && quickFilter === '';
});
```

### pageChanged

`{ page, pageCount }`, with a zero-based `page`. Fires whenever the current page changes: through the pager, `setPage()` or `update({ pagination })`, and when a filter change or a smaller dataset moves the grid to another page. A change in `pageCount` alone does not fire it; use `modelUpdated` for that.

```ts
grid.on('pageChanged', ({ page, pageCount }) => (pager.textContent = `${page + 1} / ${pageCount}`));
```

## Columns

| Event | Payload |
| --- | --- |
| `columnResized` | `{ colId, width }` |
| `columnMoved` | `{ colId, toIndex }` |
| `columnPinned` | `{ colId, pinned }` with `pinned` being `'left'`, `'right'` or `null` |
| `columnVisible` | `{ colId, hidden }` |
| `columnStateChanged` | `{ state }`, the full `ColumnState[]` after any column change |

```ts
grid.on('columnStateChanged', ({ state }) => localStorage.setItem('orders.columns', JSON.stringify(state)));
```

See [Column operations](https://docs.birchui.com/grid/column-operations.md#saving-and-restoring-column-state) for a complete persistence example.

## Full type

**`GridEvents`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridEvents<TRow = RowData> extends GridFeatureEvents<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `ready` | `{ api: GridApi<TRow> }` |  |
| `cellClick` | `CellEvent<TRow>` |  |
| `cellDoubleClick` | `CellEvent<TRow>` |  |
| `cellKeyDown` | `CellEvent<TRow>` |  |
| `cellValueChanged` | `CellValueChangedEvent<TRow>` |  |
| `rowClick` | `{ row: TRow \| undefined; displayRow: DisplayRow<TRow>; rowIndex: number; event: MouseEvent }` |  |
| `selectionChanged` | `{ selected: TRow[] }` |  |
| `sortChanged` | `{ sort: SortItem[] }` |  |
| `filterChanged` | `{ filterModel: Record<string, FilterModel>; quickFilter: string }` |  |
| `columnResized` | `{ colId: string; width: number }` |  |
| `columnMoved` | `{ colId: string; toIndex: number }` |  |
| `columnPinned` | `{ colId: string; pinned: 'left' \| 'right' \| null }` |  |
| `columnVisible` | `{ colId: string; hidden: boolean }` |  |
| `columnStateChanged` | `{ state: ColumnState[] }` |  |
| `columnGroupOpened` | `{ groupId: string; open: boolean }` |  |
| `modelUpdated` | `{ rowCount: number; displayRowCount: number }` |  |
| `focusChanged` | `{ cell: CellPosition \| null }` |  |
| `viewportScroll` | `{ top: number; left: number }` |  |
| `pageChanged` | `{ page: number; pageCount: number }` |  |
| `rowExpanded` | `{ rowId: string; expanded: boolean }` |  |
| `editStart` | `CellPosition` |  |
| `editStop` | `CellPosition & { cancelled: boolean }` |  |
| `stateChanged` | `{ state: GridState }` |  |
| `rowDragStart` | `RowDragStartEvent<TRow>` | Inherited from GridFeatureEvents. |
| `rowDragEnd` | `RowDragEndEvent<TRow>` | Inherited from GridFeatureEvents. |
| `findChanged` | `FindChangedEvent<TRow>` | Inherited from GridFeatureEvents. |
| `printStarted` | `Record<string, never>` | Inherited from GridFeatureEvents. |
| `printFinished` | `Record<string, never>` | Inherited from GridFeatureEvents. |

The event names are also available at runtime as `gridDefinition.events`, which adapters use to wire every event without listing them by hand:

```ts
import { gridDefinition } from '@birchui/core';

for (const name of gridDefinition.events) {
  grid.on(name, (payload) => console.debug(name, payload));
}
```
