본문으로 건너뛰기Skip to content
예제 첫화면Examples home

앱 저장소의 값이 바뀔 때마다 표와 합계 따라가기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.

심화Advanced
직접 써 보기Live preview앱 저장소의 값이 바뀔 때마다 표와 합계 따라가기Follow an app store: the grid and a total update with 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)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<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>
main.js
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));
example.js
// 예제 틀이 알려 주는 페이지 언어(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),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<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>
main.js
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));
example.js
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),
};