이벤트 듣기와 멈추기Subscribe to and unsubscribe from events
클릭, 선택, 정렬, 편집이 일어날 때마다 알림을 받아 기록해요. 듣기를 시작하면 멈추는 방법도 함께 얻어서, 필요 없어지면 멈출 수 있어요. '첫 번째만 듣기'도 있고, 화면이 사라질 때는 꼭 멈춰야 해요.You get a notice each time a click, selection, sort or edit happens and log it. Starting to listen also gives you the way to stop. Listening to only the first one is possible too, and everything must be stopped when the screen goes away.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<button type="button" id="start">듣기 시작</button>
<button type="button" id="stop">듣기 멈추기</button>
</div>
<div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('stop').addEventListener('click', () => actions.stop(api));const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true },
{ id: 'dept', title: '부서', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] })),
rowKey: 'id',
selection: 'multiple',
};
let write = () => { };
let listeners = [];
// on()은 리스너를 지우는 함수를 돌려줘요. 그 함수를 들고 있다가, 듣기를 멈출 때 불러요.
function listen(api) {
if (listeners.length > 0)
return write({ ko: '이미 듣고 있어요', en: 'Already listening' });
listeners = [
api.on('rowClicked', (e) => write({
ko: `행 클릭: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
en: `Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
})),
api.on('selectionChanged', (e) => write({
ko: `선택 바뀜: ${e.selectedKeys.length}행`,
en: `Selection changed: ${e.selectedKeys.length} rows`,
})),
api.on('headerClicked', (e) => write({
ko: `헤더 클릭: ${e.columnId === 'name' ? '이름' : '부서'}`,
en: `Header click: ${e.columnId === 'name' ? 'name' : 'department'}`,
})),
api.on('editCommitted', (e) => write({
ko: `편집 확정: ${e.columnId === 'name' ? '이름' : '부서'} → ${String(e.newValue)}`,
en: `Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
})),
];
write({ ko: '듣기를 시작했어요', en: 'Started listening' });
}
function stopListening() {
for (const off of listeners)
off();
listeners = [];
}
export function setup(api, log) {
write = log;
// once()는 첫 이벤트가 오면 스스로 지워져요. 헤더를 눌러 정렬하면 이 줄은 한 번만 나와요.
const offFirstSort = api.once('sortChanged', () => log({ ko: '정렬 바뀜 (첫 번째만 알려요)', en: 'Sort changed (reported only once)' }));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api) => listen(api),
stop: () => {
if (listeners.length === 0)
return write({ ko: '이미 멈춰 있어요', en: 'Already stopped' });
stopListening();
write({
ko: '듣기를 멈췄어요 (이제 아무것도 기록되지 않아요)',
en: 'Stopped listening (nothing is logged now)',
});
},
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>이벤트 듣기와 멈추기</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="start">듣기 시작</button>
<button type="button" id="stop">듣기 멈추기</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발팀', '디자인팀', '영업팀'];
const options = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true },
{ id: 'dept', title: '부서', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] })),
rowKey: 'id',
selection: 'multiple',
};
let write = () => { };
let listeners = [];
// on()은 리스너를 지우는 함수를 돌려줘요. 그 함수를 들고 있다가, 듣기를 멈출 때 불러요.
function listen(api) {
if (listeners.length > 0)
return write({ ko: '이미 듣고 있어요', en: 'Already listening' });
listeners = [
api.on('rowClicked', (e) => write({
ko: `행 클릭: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
en: `Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
})),
api.on('selectionChanged', (e) => write({
ko: `선택 바뀜: ${e.selectedKeys.length}행`,
en: `Selection changed: ${e.selectedKeys.length} rows`,
})),
api.on('headerClicked', (e) => write({
ko: `헤더 클릭: ${e.columnId === 'name' ? '이름' : '부서'}`,
en: `Header click: ${e.columnId === 'name' ? 'name' : 'department'}`,
})),
api.on('editCommitted', (e) => write({
ko: `편집 확정: ${e.columnId === 'name' ? '이름' : '부서'} → ${String(e.newValue)}`,
en: `Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
})),
];
write({ ko: '듣기를 시작했어요', en: 'Started listening' });
}
function stopListening() {
for (const off of listeners)
off();
listeners = [];
}
function setup(api, log) {
write = log;
// once()는 첫 이벤트가 오면 스스로 지워져요. 헤더를 눌러 정렬하면 이 줄은 한 번만 나와요.
const offFirstSort = api.once('sortChanged', () => log({ ko: '정렬 바뀜 (첫 번째만 알려요)', en: 'Sort changed (reported only once)' }));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
const actions = {
start: (api) => listen(api),
stop: () => {
if (listeners.length === 0)
return write({ ko: '이미 멈춰 있어요', en: 'Already stopped' });
stopListening();
write({
ko: '듣기를 멈췄어요 (이제 아무것도 기록되지 않아요)',
en: 'Stopped listening (nothing is logged now)',
});
},
};
options.ariaLabel = "이벤트 듣기와 멈추기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('stop').addEventListener('click', () => actions.stop(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.start(api)}
>듣기 시작</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.stop(api)}
>듣기 멈추기</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/react';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true },
{ id: 'dept', title: '부서', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on()은 리스너를 지우는 함수를 돌려줘요. 그 함수를 들고 있다가, 듣기를 멈출 때 불러요.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write({ ko: '이미 듣고 있어요', en: 'Already listening' });
listeners = [
api.on('rowClicked', (e) =>
write({
ko: `행 클릭: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
en: `Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
}),
),
api.on('selectionChanged', (e) =>
write({
ko: `선택 바뀜: ${e.selectedKeys.length}행`,
en: `Selection changed: ${e.selectedKeys.length} rows`,
}),
),
api.on('headerClicked', (e) =>
write({
ko: `헤더 클릭: ${e.columnId === 'name' ? '이름' : '부서'}`,
en: `Header click: ${e.columnId === 'name' ? 'name' : 'department'}`,
}),
),
api.on('editCommitted', (e) =>
write({
ko: `편집 확정: ${e.columnId === 'name' ? '이름' : '부서'} → ${String(e.newValue)}`,
en: `Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
}),
),
];
write({ ko: '듣기를 시작했어요', en: 'Started listening' });
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once()는 첫 이벤트가 오면 스스로 지워져요. 헤더를 눌러 정렬하면 이 줄은 한 번만 나와요.
const offFirstSort = api.once('sortChanged', () =>
log({ ko: '정렬 바뀜 (첫 번째만 알려요)', en: 'Sort changed (reported only once)' }),
);
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write({ ko: '이미 멈춰 있어요', en: 'Already stopped' });
stopListening();
write({
ko: '듣기를 멈췄어요 (이제 아무것도 기록되지 않아요)',
en: 'Stopped listening (nothing is logged now)',
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.start(api)">듣기 시작</button>
<button type="button" :disabled="!api" @click="api && actions.stop(api)">듣기 멈추기</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/vue';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true },
{ id: 'dept', title: '부서', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on()은 리스너를 지우는 함수를 돌려줘요. 그 함수를 들고 있다가, 듣기를 멈출 때 불러요.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write({ ko: '이미 듣고 있어요', en: 'Already listening' });
listeners = [
api.on('rowClicked', (e) =>
write({
ko: `행 클릭: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
en: `Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
}),
),
api.on('selectionChanged', (e) =>
write({
ko: `선택 바뀜: ${e.selectedKeys.length}행`,
en: `Selection changed: ${e.selectedKeys.length} rows`,
}),
),
api.on('headerClicked', (e) =>
write({
ko: `헤더 클릭: ${e.columnId === 'name' ? '이름' : '부서'}`,
en: `Header click: ${e.columnId === 'name' ? 'name' : 'department'}`,
}),
),
api.on('editCommitted', (e) =>
write({
ko: `편집 확정: ${e.columnId === 'name' ? '이름' : '부서'} → ${String(e.newValue)}`,
en: `Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
}),
),
];
write({ ko: '듣기를 시작했어요', en: 'Started listening' });
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once()는 첫 이벤트가 오면 스스로 지워져요. 헤더를 눌러 정렬하면 이 줄은 한 번만 나와요.
const offFirstSort = api.once('sortChanged', () =>
log({ ko: '정렬 바뀜 (첫 번째만 알려요)', en: 'Sort changed (reported only once)' }),
);
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write({ ko: '이미 멈춰 있어요', en: 'Already stopped' });
stopListening();
write({
ko: '듣기를 멈췄어요 (이제 아무것도 기록되지 않아요)',
en: 'Stopped listening (nothing is logged now)',
});
},
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.start(api)"
>듣기 시작</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.stop(api)"
>듣기 멈추기</button>
</div>
<mx-grid style="height: 330px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/angular';
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
}
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희'];
const depts = ['개발팀', '디자인팀', '영업팀'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 150, editable: true },
{ id: 'dept', title: '부서', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on()은 리스너를 지우는 함수를 돌려줘요. 그 함수를 들고 있다가, 듣기를 멈출 때 불러요.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write({ ko: '이미 듣고 있어요', en: 'Already listening' });
listeners = [
api.on('rowClicked', (e) =>
write({
ko: `행 클릭: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
en: `Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`,
}),
),
api.on('selectionChanged', (e) =>
write({
ko: `선택 바뀜: ${e.selectedKeys.length}행`,
en: `Selection changed: ${e.selectedKeys.length} rows`,
}),
),
api.on('headerClicked', (e) =>
write({
ko: `헤더 클릭: ${e.columnId === 'name' ? '이름' : '부서'}`,
en: `Header click: ${e.columnId === 'name' ? 'name' : 'department'}`,
}),
),
api.on('editCommitted', (e) =>
write({
ko: `편집 확정: ${e.columnId === 'name' ? '이름' : '부서'} → ${String(e.newValue)}`,
en: `Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
}),
),
];
write({ ko: '듣기를 시작했어요', en: 'Started listening' });
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once()는 첫 이벤트가 오면 스스로 지워져요. 헤더를 눌러 정렬하면 이 줄은 한 번만 나와요.
const offFirstSort = api.once('sortChanged', () =>
log({ ko: '정렬 바뀜 (첫 번째만 알려요)', en: 'Sort changed (reported only once)' }),
);
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write({ ko: '이미 멈춰 있어요', en: 'Already stopped' });
stopListening();
write({
ko: '듣기를 멈췄어요 (이제 아무것도 기록되지 않아요)',
en: 'Stopped listening (nothing is logged now)',
});
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<button type="button" id="start">Start listening</button>
<button type="button" id="stop">Stop listening</button>
</div>
<div id="grid" style="height: 330px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('stop').addEventListener('click', () => actions.stop(api));const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options = {
columns: [
{ id: 'name', title: 'Name', width: 150, editable: true },
{ id: 'dept', title: 'Department', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] })),
rowKey: 'id',
selection: 'multiple',
};
let write = () => { };
let listeners = [];
// on() returns a function that removes the listener. Keep it, and call it when you stop listening.
function listen(api) {
if (listeners.length > 0)
return write('Already listening');
listeners = [
api.on('rowClicked', (e) => write(`Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`)),
api.on('selectionChanged', (e) => write(`Selection changed: ${e.selectedKeys.length} rows`)),
api.on('headerClicked', (e) => write(`Header click: ${e.columnId === 'name' ? 'name' : 'department'}`)),
api.on('editCommitted', (e) => write(`Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`)),
];
write('Started listening');
}
function stopListening() {
for (const off of listeners)
off();
listeners = [];
}
export function setup(api, log) {
write = log;
// once() removes itself after the first event. If you sort by clicking a header, this line appears only once.
const offFirstSort = api.once('sortChanged', () => log('Sort changed (reported only once)'));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api) => listen(api),
stop: () => {
if (listeners.length === 0)
return write('Already stopped');
stopListening();
write('Stopped listening (nothing is logged now)');
},
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Subscribe to and unsubscribe from events</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="start">Start listening</button>
<button type="button" id="stop">Stop listening</button>
</div>
<div id="grid" style="height: 330px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const depts = ['Dev', 'Design', 'Sales'];
const options = {
columns: [
{ id: 'name', title: 'Name', width: 150, editable: true },
{ id: 'dept', title: 'Department', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] })),
rowKey: 'id',
selection: 'multiple',
};
let write = () => { };
let listeners = [];
// on() returns a function that removes the listener. Keep it, and call it when you stop listening.
function listen(api) {
if (listeners.length > 0)
return write('Already listening');
listeners = [
api.on('rowClicked', (e) => write(`Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`)),
api.on('selectionChanged', (e) => write(`Selection changed: ${e.selectedKeys.length} rows`)),
api.on('headerClicked', (e) => write(`Header click: ${e.columnId === 'name' ? 'name' : 'department'}`)),
api.on('editCommitted', (e) => write(`Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`)),
];
write('Started listening');
}
function stopListening() {
for (const off of listeners)
off();
listeners = [];
}
function setup(api, log) {
write = log;
// once() removes itself after the first event. If you sort by clicking a header, this line appears only once.
const offFirstSort = api.once('sortChanged', () => log('Sort changed (reported only once)'));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
const actions = {
start: (api) => listen(api),
stop: () => {
if (listeners.length === 0)
return write('Already stopped');
stopListening();
write('Stopped listening (nothing is logged now)');
},
};
options.ariaLabel = "Subscribe to and unsubscribe from events";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('start').addEventListener('click', () => actions.start(api));
document.getElementById('stop').addEventListener('click', () => actions.stop(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<button
type="button"
disabled={!api}
onClick={() => api && actions.start(api)}
>Start listening</button>
<button
type="button"
disabled={!api}
onClick={() => api && actions.stop(api)}
>Stop listening</button>
</div>
<Grid style={{ height: 330 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 150, editable: true },
{ id: 'dept', title: 'Department', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on() returns a function that removes the listener. Keep it, and call it when you stop listening.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write('Already listening');
listeners = [
api.on('rowClicked', (e) => write(`Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`)),
api.on('selectionChanged', (e) => write(`Selection changed: ${e.selectedKeys.length} rows`)),
api.on('headerClicked', (e) =>
write(`Header click: ${e.columnId === 'name' ? 'name' : 'department'}`),
),
api.on('editCommitted', (e) =>
write(
`Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
),
),
];
write('Started listening');
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once() removes itself after the first event. If you sort by clicking a header, this line appears only once.
const offFirstSort = api.once('sortChanged', () => log('Sort changed (reported only once)'));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write('Already stopped');
stopListening();
write('Stopped listening (nothing is logged now)');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<button type="button" :disabled="!api" @click="api && actions.start(api)">Start listening</button>
<button type="button" :disabled="!api" @click="api && actions.stop(api)">Stop listening</button>
</div>
<Grid style="height: 330px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 150, editable: true },
{ id: 'dept', title: 'Department', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on() returns a function that removes the listener. Keep it, and call it when you stop listening.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write('Already listening');
listeners = [
api.on('rowClicked', (e) => write(`Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`)),
api.on('selectionChanged', (e) => write(`Selection changed: ${e.selectedKeys.length} rows`)),
api.on('headerClicked', (e) =>
write(`Header click: ${e.columnId === 'name' ? 'name' : 'department'}`),
),
api.on('editCommitted', (e) =>
write(
`Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
),
),
];
write('Started listening');
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once() removes itself after the first event. If you sort by clicking a header, this line appears only once.
const offFirstSort = api.once('sortChanged', () => log('Sort changed (reported only once)'));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write('Already stopped');
stopListening();
write('Stopped listening (nothing is logged now)');
},
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<button
type="button"
[disabled]="!api"
(click)="api && actions.start(api)"
>Start listening</button>
<button
type="button"
[disabled]="!api"
(click)="api && actions.stop(api)"
>Stop listening</button>
</div>
<mx-grid style="height: 330px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions, Unsubscribe } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
}
const names = [
'Liam Carter',
'Emma Stone',
'Noah Reed',
'Olivia Hayes',
'Ethan Brooks',
'Sophia Bell',
];
const depts = ['Dev', 'Design', 'Sales'];
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 150, editable: true },
{ id: 'dept', title: 'Department', width: 130 },
],
rows: names.map((name, i) => ({ id: i + 1, name, dept: depts[i % 3] as string })),
rowKey: 'id',
selection: 'multiple',
};
let write: (message: LogText) => void = () => {};
let listeners: Unsubscribe[] = [];
// on() returns a function that removes the listener. Keep it, and call it when you stop listening.
function listen(api: GridApi<Row>): void {
if (listeners.length > 0) return write('Already listening');
listeners = [
api.on('rowClicked', (e) => write(`Row click: ${api.getRowByKey(e.rowKey)?.name ?? e.rowKey}`)),
api.on('selectionChanged', (e) => write(`Selection changed: ${e.selectedKeys.length} rows`)),
api.on('headerClicked', (e) =>
write(`Header click: ${e.columnId === 'name' ? 'name' : 'department'}`),
),
api.on('editCommitted', (e) =>
write(
`Edit confirmed: ${e.columnId === 'name' ? 'name' : 'department'} → ${String(e.newValue)}`,
),
),
];
write('Started listening');
}
function stopListening(): void {
for (const off of listeners) off();
listeners = [];
}
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
write = log;
// once() removes itself after the first event. If you sort by clicking a header, this line appears only once.
const offFirstSort = api.once('sortChanged', () => log('Sort changed (reported only once)'));
listen(api);
return () => {
stopListening();
offFirstSort();
};
}
export const actions = {
start: (api: GridApi<Row>) => listen(api),
stop: () => {
if (listeners.length === 0) return write('Already stopped');
stopListening();
write('Stopped listening (nothing is logged now)');
},
};