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

빠른 변경을 모아서 한 번에 적용하기Batch fast changes into one update

transactBatched로 준 변경은 transactionWaitMs 동안 모였다가 순서대로 하나로 합쳐져 한 번에 적용돼요. 적용되면 rowsChanged와 transactionsFlushed가 한 번씩 나가고 되돌리기 기록에는 남지 않아요.Changes given to transactBatched are collected for transactionWaitMs, merged in order and applied together. One rowsChanged and one transactionsFlushed are emitted, and nothing is added to the undo history.

활용Intermediate
직접 써 보기Live preview빠른 변경을 모아서 한 번에 적용하기Batch fast changes into one update

코드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="burst">다섯 번 모아서 수정</button>
    <button type="button" id="addAndEdit">추가 후 수정</button>
    <button type="button" id="now">지금 적용</button>
  </div>
  <div id="grid" style="height: 280px"></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('burst').addEventListener('click', () => actions.burst(api));
document.getElementById('addAndEdit').addEventListener('click', () => actions.addAndEdit(api));
document.getElementById('now').addEventListener('click', () => actions.now(api));
example.js
const rows = Array.from({ length: 6 }, (_, i) => ({
  id: i + 1,
  name: `항목 ${i + 1}`,
  count: 0,
}));
// transactBatched는 짧은 시간 안에 들어온 변경을 순서대로 하나로 합쳐 한 번에 적용해요.
// 여러 번 불러도 rowsChanged와 transactionsFlushed는 한 번씩만 나가요(transactionWaitMs, 기본 50ms).
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 120 },
    { id: 'count', title: '횟수', kind: 'number', width: 100 },
  ],
  rows,
  rowKey: 'id',
  changeFlash: true,
  transactionWaitMs: 300,
};
let pending = 0;
let logLine = null;
let note = null;
// 대기 중인 변경이 없을 때의 안내를 표 위쪽에 role=status로 보여요.
function say(api, text) {
  if (note === null) {
    const host = api.getGridElement().parentElement;
    host.style.position = 'relative';
    note = document.createElement('div');
    note.setAttribute('role', 'status');
    note.style.cssText =
      'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
    host.append(note);
  }
  note.textContent = text;
}
export function setup(api, log) {
  pending = 0;
  note = null;
  logLine = log;
  const offs = [
    api.on('transactionsFlushed', () => {
      pending = 0;
      if (note !== null)
        note.textContent = '';
    }),
    api.on('rowsChanged', (e) => log({
      ko: `rowsChanged: ${e.reason}, ${e.count}개`,
      en: `rowsChanged: ${e.reason}, ${e.count}`,
    })),
    api.on('transactionsFlushed', (e) => log({
      ko: `transactionsFlushed: ${e.transactions}건 합침 (추가 ${e.added}, 수정 ${e.updated}, 삭제 ${e.removed})`,
      en: `transactionsFlushed: ${e.transactions} merged (added ${e.added}, updated ${e.updated}, removed ${e.removed})`,
    })),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  burst: (api) => {
    for (let i = 0; i < 5; i++) {
      const row = api.getRowByKey(1 + i);
      if (row) {
        api.transactBatched({ update: [{ ...row, count: row.count + 1 }] });
        pending += 1;
      }
    }
  },
  addAndEdit: (api) => {
    const id = 100 + api.getRowCount();
    pending += 2;
    api.transactBatched({ add: [{ id, name: `새 ${id}`, count: 1 }] });
    api.transactBatched({ update: [{ id, name: `새 ${id}`, count: 2 }] });
  },
  now: (api) => {
    if (pending === 0) {
      say(api, '지금 적용할 변경이 없어요');
      logLine?.({
        ko: '지금 적용할 변경이 없어요. 먼저 다섯 번 모아서 수정이나 추가 후 수정을 눌러 보세요',
        en: 'Nothing is waiting to apply. Press Five batched updates or Add then edit first',
      });
      return;
    }
    api.flushTransactions();
  },
};

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="burst">Five batched updates</button>
    <button type="button" id="addAndEdit">Add then edit</button>
    <button type="button" id="now">Apply now</button>
  </div>
  <div id="grid" style="height: 280px"></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('burst').addEventListener('click', () => actions.burst(api));
document.getElementById('addAndEdit').addEventListener('click', () => actions.addAndEdit(api));
document.getElementById('now').addEventListener('click', () => actions.now(api));
example.js
const rows = Array.from({ length: 6 }, (_, i) => ({
  id: i + 1,
  name: `Item ${i + 1}`,
  count: 0,
}));
// transactBatched merges changes that arrive within a short time, in order, and applies them at once.
// Even if called many times, rowsChanged and transactionsFlushed fire only once each (transactionWaitMs, default 50ms).
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 120 },
    { id: 'count', title: 'Count', kind: 'number', width: 100 },
  ],
  rows,
  rowKey: 'id',
  changeFlash: true,
  transactionWaitMs: 300,
};
let pending = 0;
let logLine = null;
let note = null;
// Shows the "nothing is waiting" notice over the grid as role=status.
function say(api, text) {
  if (note === null) {
    const host = api.getGridElement().parentElement;
    host.style.position = 'relative';
    note = document.createElement('div');
    note.setAttribute('role', 'status');
    note.style.cssText =
      'position: absolute; right: 8px; bottom: 8px; z-index: 5; padding: 2px 8px; font-size: 12px; border-radius: 4px; pointer-events: none; background: var(--mxg-bg, #fff); color: var(--mxg-fg, #1f2933); border: 1px solid var(--mxg-border, #d9dee5);';
    host.append(note);
  }
  note.textContent = text;
}
export function setup(api, log) {
  pending = 0;
  note = null;
  logLine = log;
  const offs = [
    api.on('transactionsFlushed', () => {
      pending = 0;
      if (note !== null)
        note.textContent = '';
    }),
    api.on('rowsChanged', (e) => log(`rowsChanged: ${e.reason}, ${e.count}`)),
    api.on('transactionsFlushed', (e) => log(`transactionsFlushed: ${e.transactions} merged (added ${e.added}, updated ${e.updated}, removed ${e.removed})`)),
  ];
  return () => offs.forEach((off) => off());
}
export const actions = {
  burst: (api) => {
    for (let i = 0; i < 5; i++) {
      const row = api.getRowByKey(1 + i);
      if (row) {
        api.transactBatched({ update: [{ ...row, count: row.count + 1 }] });
        pending += 1;
      }
    }
  },
  addAndEdit: (api) => {
    const id = 100 + api.getRowCount();
    pending += 2;
    api.transactBatched({ add: [{ id, name: `New ${id}`, count: 1 }] });
    api.transactBatched({ update: [{ id, name: `New ${id}`, count: 2 }] });
  },
  now: (api) => {
    if (pending === 0) {
      say(api, 'Nothing is waiting to apply');
      logLine?.('Nothing is waiting to apply. Press Five batched updates or Add then edit first');
      return;
    }
    api.flushTransactions();
  },
};