앱 저장소의 값이 바뀔 때마다 표와 합계 따라가기Follow an app store: the grid and a total update with it
앱이 들고 있는 값이 1초마다 새로 바뀌면 표와 아래 합계가 함께 따라가요. 행은 한 곳에만 두고, 합계는 따로 저장하지 않고 행에서 계산해요. 라이브러리를 더 설치하지 않고, 프레임워크가 기본으로 주는 작은 저장소만 써요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.When the app's own data changes every second, the grid and the total follow it. Rows live in one place and the total is computed from them instead of stored. No extra library is installed; only the small store each framework provides is used. The React, Vue and Angular tabs hold the same example written the way each framework does it.
실행 화면은 JavaScript 버전이에요. 아래 탭의 React·Vue·Angular 코드는 같은 예제를 각 프레임워크로 직접 쓴 코드예요.The preview runs the JavaScript version. The React, Vue, Angular tabs below hold the same example written for each framework.
코드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="pause">멈추기</button>
<button type="button" id="resume">다시 받기</button>
</div>
<div id="grid" style="height: 420px"></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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
export const initialRows = [
{ id: 1, name: '사과', price: 1200 },
{ id: 2, name: '배', price: 1800 },
{ id: 3, name: '포도', price: 3500 },
{ id: 4, name: '귤', price: 900 },
];
/** 서버에서 새 값이 온 것처럼, 모든 가격을 조금씩 바꾼 새 행 목록을 돌려줘요. 원래 목록은 건드리지 않아요. */
export function tickRows(rows, step) {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** 합계처럼 행에서 계산되는 값은 따로 저장하지 않고 필요할 때 다시 계산해요. */
export function totalOf(rows) {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value) => `${value.toLocaleString('ko-KR')}원`;
export const options = {
columns: [
{ id: 'name', title: '품목', width: 140 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// 이 화면(JavaScript 버전): 1초마다 값이 바뀌고, 합계 줄도 함께 바뀌어요.
let timer;
let line = null;
let step = 0;
const start = (api, log) => {
if (timer !== undefined)
return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = L(`가격 합계: ${won(totalOf(next))}`, `Price total: ${won(totalOf(next))}`);
}, 1000);
log({ ko: '1초마다 새 값을 받기 시작했어요', en: 'Started receiving new values every second' });
};
const stop = (log) => {
if (timer === undefined)
return;
clearInterval(timer);
timer = undefined;
log({ ko: '새 값 받기를 멈췄어요', en: 'Stopped receiving new values' });
};
let say = () => { };
export function setup(api, log) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L(`가격 합계: ${won(totalOf(initialRows))}`, `Price total: ${won(totalOf(initialRows))}`);
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => { });
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api) => stop(say),
resume: (api) => start(api, say),
};<!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="pause">멈추기</button>
<button type="button" id="resume">다시 받기</button>
</div>
<div id="grid" style="height: 420px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const initialRows = [
{ id: 1, name: '사과', price: 1200 },
{ id: 2, name: '배', price: 1800 },
{ id: 3, name: '포도', price: 3500 },
{ id: 4, name: '귤', price: 900 },
];
/** 서버에서 새 값이 온 것처럼, 모든 가격을 조금씩 바꾼 새 행 목록을 돌려줘요. 원래 목록은 건드리지 않아요. */
function tickRows(rows, step) {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** 합계처럼 행에서 계산되는 값은 따로 저장하지 않고 필요할 때 다시 계산해요. */
function totalOf(rows) {
return rows.reduce((sum, row) => sum + row.price, 0);
}
const won = (value) => `${value.toLocaleString('ko-KR')}원`;
const options = {
columns: [
{ id: 'name', title: '품목', width: 140 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// 이 화면(JavaScript 버전): 1초마다 값이 바뀌고, 합계 줄도 함께 바뀌어요.
let timer;
let line = null;
let step = 0;
const start = (api, log) => {
if (timer !== undefined)
return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = L(`가격 합계: ${won(totalOf(next))}`, `Price total: ${won(totalOf(next))}`);
}, 1000);
log({ ko: '1초마다 새 값을 받기 시작했어요', en: 'Started receiving new values every second' });
};
const stop = (log) => {
if (timer === undefined)
return;
clearInterval(timer);
timer = undefined;
log({ ko: '새 값 받기를 멈췄어요', en: 'Stopped receiving new values' });
};
let say = () => { };
function setup(api, log) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L(`가격 합계: ${won(totalOf(initialRows))}`, `Price total: ${won(totalOf(initialRows))}`);
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => { });
line?.remove();
line = null;
};
}
const actions = {
pause: (_api) => stop(say),
resume: (api) => start(api, say),
};
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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Grid } from '@maxgrid/react';
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { initialRows, options as base, tickRows, totalOf, won, type Row } from './example';
// 작은 저장소: 행을 한 곳에 두고, 바뀌면 구독한 화면에 알려요. 라이브러리 없이도 이 정도면 돼요.
function createStore() {
let rows: Row[] = initialRows;
let step = 0;
const listeners = new Set<() => void>();
return {
subscribe(listener: () => void) {
listeners.add(listener);
return () => void listeners.delete(listener);
},
getSnapshot: () => rows,
tick() {
step += 1;
rows = tickRows(rows, step);
listeners.forEach((listener) => listener());
},
};
}
export function ExampleGrid() {
const [store] = useState(createStore);
const rows = useSyncExternalStore(store.subscribe, store.getSnapshot);
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
useEffect(() => {
const timer = setInterval(store.tick, 1000);
return () => clearInterval(timer);
}, [store]);
// 합계는 저장하지 않고 rows에서 계산해요. rows가 바뀔 때만 다시 계산해요.
const total = useMemo(() => totalOf(rows), [rows]);
const options = useMemo(() => ({ ...base, rows }), [rows]);
return (
<>
<p>가격 합계: {won(total)}</p>
<div style={{ height: 220 }}>
<Grid<Row> options={options} />
</div>
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: '사과', price: 1200 },
{ id: 2, name: '배', price: 1800 },
{ id: 3, name: '포도', price: 3500 },
{ id: 4, name: '귤', price: 900 },
];
/** 서버에서 새 값이 온 것처럼, 모든 가격을 조금씩 바꾼 새 행 목록을 돌려줘요. 원래 목록은 건드리지 않아요. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** 합계처럼 행에서 계산되는 값은 따로 저장하지 않고 필요할 때 다시 계산해요. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `${value.toLocaleString('ko-KR')}원`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 140 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// 이 화면(JavaScript 버전): 1초마다 값이 바뀌고, 합계 줄도 함께 바뀌어요.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = L(
`가격 합계: ${won(totalOf(next))}`,
`Price total: ${won(totalOf(next))}`,
);
}, 1000);
log({ ko: '1초마다 새 값을 받기 시작했어요', en: 'Started receiving new values every second' });
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log({ ko: '새 값 받기를 멈췄어요', en: 'Stopped receiving new values' });
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L(
`가격 합계: ${won(totalOf(initialRows))}`,
`Price total: ${won(totalOf(initialRows))}`,
);
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { Grid } from '@maxgrid/vue';
import { computed, onBeforeUnmount, onMounted, shallowRef } from 'vue';
import { initialRows, options as base, tickRows, totalOf, won } from './example';
// 따로 저장소 라이브러리 없이도, 값 하나(shallowRef)가 저장소 역할을 해요.
// 합계는 저장하지 않고 computed로 rows에서 계산해요.
const rows = shallowRef(initialRows);
const total = computed(() => totalOf(rows.value));
const options = computed(() => ({ ...base, rows: rows.value }));
let timer: ReturnType<typeof setInterval> | undefined;
let step = 0;
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
onMounted(() => {
timer = setInterval(() => {
step += 1;
rows.value = tickRows(rows.value, step);
}, 1000);
});
onBeforeUnmount(() => clearInterval(timer));
</script>
<template>
<p>가격 합계: {{ won(total) }}</p>
<Grid style="height: 220px" :options="options" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: '사과', price: 1200 },
{ id: 2, name: '배', price: 1800 },
{ id: 3, name: '포도', price: 3500 },
{ id: 4, name: '귤', price: 900 },
];
/** 서버에서 새 값이 온 것처럼, 모든 가격을 조금씩 바꾼 새 행 목록을 돌려줘요. 원래 목록은 건드리지 않아요. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** 합계처럼 행에서 계산되는 값은 따로 저장하지 않고 필요할 때 다시 계산해요. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `${value.toLocaleString('ko-KR')}원`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 140 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// 이 화면(JavaScript 버전): 1초마다 값이 바뀌고, 합계 줄도 함께 바뀌어요.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = L(
`가격 합계: ${won(totalOf(next))}`,
`Price total: ${won(totalOf(next))}`,
);
}, 1000);
log({ ko: '1초마다 새 값을 받기 시작했어요', en: 'Started receiving new values every second' });
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log({ ko: '새 값 받기를 멈췄어요', en: 'Stopped receiving new values' });
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L(
`가격 합계: ${won(totalOf(initialRows))}`,
`Price total: ${won(totalOf(initialRows))}`,
);
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { GridComponent } from '@maxgrid/angular';
import { initialRows, options as base, tickRows, totalOf, won } from './example';
// 따로 저장소 라이브러리 없이도, signal 하나가 저장소 역할을 해요.
// 합계는 저장하지 않고 computed로 rows에서 계산해요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<p>가격 합계: {{ totalText() }}</p>
<mx-grid style="height: 220px" [options]="options()" />
`,
})
export class ExampleGridComponent {
readonly rows = signal(initialRows);
readonly totalText = computed(() => won(totalOf(this.rows())));
readonly options = computed(() => ({ ...base, rows: this.rows() }));
private step = 0;
constructor() {
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
const timer = setInterval(() => {
this.step += 1;
this.rows.update((rows) => tickRows(rows, this.step));
}, 1000);
inject(DestroyRef).onDestroy(() => clearInterval(timer));
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: '사과', price: 1200 },
{ id: 2, name: '배', price: 1800 },
{ id: 3, name: '포도', price: 3500 },
{ id: 4, name: '귤', price: 900 },
];
/** 서버에서 새 값이 온 것처럼, 모든 가격을 조금씩 바꾼 새 행 목록을 돌려줘요. 원래 목록은 건드리지 않아요. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** 합계처럼 행에서 계산되는 값은 따로 저장하지 않고 필요할 때 다시 계산해요. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `${value.toLocaleString('ko-KR')}원`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '품목', width: 140 },
{
id: 'price',
title: '가격',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// 이 화면(JavaScript 버전): 1초마다 값이 바뀌고, 합계 줄도 함께 바뀌어요.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = L(
`가격 합계: ${won(totalOf(next))}`,
`Price total: ${won(totalOf(next))}`,
);
}, 1000);
log({ ko: '1초마다 새 값을 받기 시작했어요', en: 'Started receiving new values every second' });
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log({ ko: '새 값 받기를 멈췄어요', en: 'Stopped receiving new values' });
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = L(
`가격 합계: ${won(totalOf(initialRows))}`,
`Price total: ${won(totalOf(initialRows))}`,
);
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};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="pause">Pause</button>
<button type="button" id="resume">Resume</button>
</div>
<div id="grid" style="height: 420px"></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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));export const initialRows = [
{ id: 1, name: 'Apple', price: 1200 },
{ id: 2, name: 'Pear', price: 1800 },
{ id: 3, name: 'Grape', price: 3500 },
{ id: 4, name: 'Orange', price: 900 },
];
/** Returns a new row list with every price changed a little, as if new values came from the server. The original list is untouched. */
export function tickRows(rows, step) {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** A value computed from rows, such as a total, is not stored separately and is recomputed when needed. */
export function totalOf(rows) {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value) => `$${value.toLocaleString('en-US')}`;
export const options = {
columns: [
{ id: 'name', title: 'Item', width: 140 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// This screen (JavaScript version): the values change every second, and the total line changes with them.
let timer;
let line = null;
let step = 0;
const start = (api, log) => {
if (timer !== undefined)
return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = `Price total: ${won(totalOf(next))}`;
}, 1000);
log('Started receiving new values every second');
};
const stop = (log) => {
if (timer === undefined)
return;
clearInterval(timer);
timer = undefined;
log('Stopped receiving new values');
};
let say = () => { };
export function setup(api, log) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = `Price total: ${won(totalOf(initialRows))}`;
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => { });
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api) => stop(say),
resume: (api) => start(api, say),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Follow an app store: the grid and a total update with it</title>
</head>
<body>
<div class="toolbar">
<button type="button" id="pause">Pause</button>
<button type="button" id="resume">Resume</button>
</div>
<div id="grid" style="height: 420px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const initialRows = [
{ id: 1, name: 'Apple', price: 1200 },
{ id: 2, name: 'Pear', price: 1800 },
{ id: 3, name: 'Grape', price: 3500 },
{ id: 4, name: 'Orange', price: 900 },
];
/** Returns a new row list with every price changed a little, as if new values came from the server. The original list is untouched. */
function tickRows(rows, step) {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** A value computed from rows, such as a total, is not stored separately and is recomputed when needed. */
function totalOf(rows) {
return rows.reduce((sum, row) => sum + row.price, 0);
}
const won = (value) => `$${value.toLocaleString('en-US')}`;
const options = {
columns: [
{ id: 'name', title: 'Item', width: 140 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// This screen (JavaScript version): the values change every second, and the total line changes with them.
let timer;
let line = null;
let step = 0;
const start = (api, log) => {
if (timer !== undefined)
return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line)
line.textContent = `Price total: ${won(totalOf(next))}`;
}, 1000);
log('Started receiving new values every second');
};
const stop = (log) => {
if (timer === undefined)
return;
clearInterval(timer);
timer = undefined;
log('Stopped receiving new values');
};
let say = () => { };
function setup(api, log) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = `Price total: ${won(totalOf(initialRows))}`;
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => { });
line?.remove();
line = null;
};
}
const actions = {
pause: (_api) => stop(say),
resume: (api) => start(api, say),
};
options.ariaLabel = "Follow an app store: the grid and a total update with it";
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('pause').addEventListener('click', () => actions.pause(api));
document.getElementById('resume').addEventListener('click', () => actions.resume(api));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Grid } from '@maxgrid/react';
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { initialRows, options as base, tickRows, totalOf, won, type Row } from './example';
// 작은 저장소: 행을 한 곳에 두고, 바뀌면 구독한 화면에 알려요. 라이브러리 없이도 이 정도면 돼요.
function createStore() {
let rows: Row[] = initialRows;
let step = 0;
const listeners = new Set<() => void>();
return {
subscribe(listener: () => void) {
listeners.add(listener);
return () => void listeners.delete(listener);
},
getSnapshot: () => rows,
tick() {
step += 1;
rows = tickRows(rows, step);
listeners.forEach((listener) => listener());
},
};
}
export function ExampleGrid() {
const [store] = useState(createStore);
const rows = useSyncExternalStore(store.subscribe, store.getSnapshot);
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
useEffect(() => {
const timer = setInterval(store.tick, 1000);
return () => clearInterval(timer);
}, [store]);
// 합계는 저장하지 않고 rows에서 계산해요. rows가 바뀔 때만 다시 계산해요.
const total = useMemo(() => totalOf(rows), [rows]);
const options = useMemo(() => ({ ...base, rows }), [rows]);
return (
<>
<p>가격 합계: {won(total)}</p>
<div style={{ height: 220 }}>
<Grid<Row> options={options} />
</div>
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: 'Apple', price: 1200 },
{ id: 2, name: 'Pear', price: 1800 },
{ id: 3, name: 'Grape', price: 3500 },
{ id: 4, name: 'Orange', price: 900 },
];
/** Returns a new row list with every price changed a little, as if new values came from the server. The original list is untouched. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** A value computed from rows, such as a total, is not stored separately and is recomputed when needed. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `$${value.toLocaleString('en-US')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 140 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// This screen (JavaScript version): the values change every second, and the total line changes with them.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line) line.textContent = `Price total: ${won(totalOf(next))}`;
}, 1000);
log('Started receiving new values every second');
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log('Stopped receiving new values');
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = `Price total: ${won(totalOf(initialRows))}`;
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { Grid } from '@maxgrid/vue';
import { computed, onBeforeUnmount, onMounted, shallowRef } from 'vue';
import { initialRows, options as base, tickRows, totalOf, won } from './example';
// 따로 저장소 라이브러리 없이도, 값 하나(shallowRef)가 저장소 역할을 해요.
// 합계는 저장하지 않고 computed로 rows에서 계산해요.
const rows = shallowRef(initialRows);
const total = computed(() => totalOf(rows.value));
const options = computed(() => ({ ...base, rows: rows.value }));
let timer: ReturnType<typeof setInterval> | undefined;
let step = 0;
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
onMounted(() => {
timer = setInterval(() => {
step += 1;
rows.value = tickRows(rows.value, step);
}, 1000);
});
onBeforeUnmount(() => clearInterval(timer));
</script>
<template>
<p>가격 합계: {{ won(total) }}</p>
<Grid style="height: 220px" :options="options" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: 'Apple', price: 1200 },
{ id: 2, name: 'Pear', price: 1800 },
{ id: 3, name: 'Grape', price: 3500 },
{ id: 4, name: 'Orange', price: 900 },
];
/** Returns a new row list with every price changed a little, as if new values came from the server. The original list is untouched. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** A value computed from rows, such as a total, is not stored separately and is recomputed when needed. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `$${value.toLocaleString('en-US')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 140 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// This screen (JavaScript version): the values change every second, and the total line changes with them.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line) line.textContent = `Price total: ${won(totalOf(next))}`;
}, 1000);
log('Started receiving new values every second');
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log('Stopped receiving new values');
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = `Price total: ${won(totalOf(initialRows))}`;
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, DestroyRef, computed, inject, signal } from '@angular/core';
import { GridComponent } from '@maxgrid/angular';
import { initialRows, options as base, tickRows, totalOf, won } from './example';
// 따로 저장소 라이브러리 없이도, signal 하나가 저장소 역할을 해요.
// 합계는 저장하지 않고 computed로 rows에서 계산해요.
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<p>가격 합계: {{ totalText() }}</p>
<mx-grid style="height: 220px" [options]="options()" />
`,
})
export class ExampleGridComponent {
readonly rows = signal(initialRows);
readonly totalText = computed(() => won(totalOf(this.rows())));
readonly options = computed(() => ({ ...base, rows: this.rows() }));
private step = 0;
constructor() {
// 1초마다 새 값을 받아요. 화면이 사라질 때 타이머를 꼭 멈춰요.
const timer = setInterval(() => {
this.step += 1;
this.rows.update((rows) => tickRows(rows, this.step));
}, 1000);
inject(DestroyRef).onDestroy(() => clearInterval(timer));
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
price: number;
}
export const initialRows: Row[] = [
{ id: 1, name: 'Apple', price: 1200 },
{ id: 2, name: 'Pear', price: 1800 },
{ id: 3, name: 'Grape', price: 3500 },
{ id: 4, name: 'Orange', price: 900 },
];
/** Returns a new row list with every price changed a little, as if new values came from the server. The original list is untouched. */
export function tickRows(rows: readonly Row[], step: number): Row[] {
return rows.map((row, i) => ({
...row,
price: Math.max(100, row.price + (((step + i) % 5) - 2) * 50),
}));
}
/** A value computed from rows, such as a total, is not stored separately and is recomputed when needed. */
export function totalOf(rows: readonly Row[]): number {
return rows.reduce((sum, row) => sum + row.price, 0);
}
export const won = (value: number): string => `$${value.toLocaleString('en-US')}`;
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Item', width: 140 },
{
id: 'price',
title: 'Price',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => won(Number(value)),
},
],
rows: initialRows,
rowKey: 'id',
};
// This screen (JavaScript version): the values change every second, and the total line changes with them.
let timer: ReturnType<typeof setInterval> | undefined;
let line: HTMLElement | null = null;
let step = 0;
const start = (api: GridApi<Row>, log: (message: LogText) => void): void => {
if (timer !== undefined) return;
timer = setInterval(() => {
step += 1;
const next = tickRows(api.getRows(), step);
api.setRows(next);
if (line) line.textContent = `Price total: ${won(totalOf(next))}`;
}, 1000);
log('Started receiving new values every second');
};
const stop = (log: (message: LogText) => void): void => {
if (timer === undefined) return;
clearInterval(timer);
timer = undefined;
log('Stopped receiving new values');
};
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
step = 0;
line = document.createElement('div');
line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
line.textContent = `Price total: ${won(totalOf(initialRows))}`;
document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
start(api, log);
return () => {
stop(() => {});
line?.remove();
line = null;
};
}
export const actions = {
pause: (_api: GridApi<Row>) => stop(say),
resume: (api: GridApi<Row>) => start(api, say),
};