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

고친 행 수와 저장 버튼 한 줄로 보여 주기A save bar with pending count and a save button

표에서 고친 행이 몇 개인지, 저장하는 중인지를 한 줄로 보여 주고 저장·되돌리기 버튼을 붙여요. 고친 내용 추적과 저장은 표가 하고, 프레임워크 쪽 도우미는 그 값을 화면 상태로 모아 주기만 해요. React, Vue, Angular 탭에는 각 프레임워크의 방식으로 쓴 같은 예제가 들어 있어요.A bar shows how many rows were edited and whether a save is running, with Save and Discard buttons. The grid does the tracking and saving; the framework helper only gathers those values into screen state. The React, Vue and Angular tabs hold the same example written the way each framework does it.

심화Advanced
직접 써 보기Live preview고친 행 수와 저장 버튼 한 줄로 보여 주기A save bar with pending count and a save button

실행 화면은 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="raise">둘째 행 월급 10 올리기</button>
    <button type="button" id="makeBad">첫 행 월급을 -1로</button>
    <button type="button" id="save">저장</button>
    <button type="button" id="discard">되돌리기</button>
  </div>
  <div id="grid" style="height: 440px"></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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
/** 서버에 저장하는 척하는 함수예요. 0.5초 뒤에 끝나고, 월급이 0보다 작은 행은 거절해요. */
export const saveToServer = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 500));
  const failed = changes
    .filter((c) => c.state !== 'removed' && c.row.salary < 0)
    .map((c) => ({
    key: c.key,
    message: L('월급은 0보다 작을 수 없어요', 'Pay cannot be less than 0'),
  }));
  return { failed };
};
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 130, editable: true, validation: { required: true } },
    { id: 'dept', title: '부서', width: 120, editable: true },
    { id: 'salary', title: '월급(만원)', kind: 'number', width: 120, align: 'end', editable: true },
  ],
  rows: [
    { id: 1, name: '김민준', dept: '개발팀', salary: 520 },
    { id: 2, name: '이서연', dept: '디자인팀', salary: 480 },
    { id: 3, name: '박지호', dept: '영업팀', salary: 450 },
  ],
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: saveToServer,
};
/** 저장 결과를 한글로 풀어 주는 말이에요. */
const SAVE_WORDS_EN = {
  saved: 'All saved',
  partial: 'Partly saved',
  failed: 'Could not save',
  invalid: 'Not saved because a value needs fixing',
  empty: 'No changes to save',
};
export const SAVE_WORDS = {
  saved: '모두 저장됐어요',
  partial: '일부만 저장됐어요',
  failed: '저장하지 못했어요',
  invalid: '고칠 값이 있어서 저장하지 않았어요',
  empty: '저장할 변경이 없어요',
};
// 이 화면(JavaScript 버전): 고친 개수와 저장 중 표시를 표 위 한 줄로 보여 줘요.
let line = null;
let say = () => { };
export function setup(api, log) {
  say = log;
  line = document.createElement('div');
  line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
  line.textContent = L('저장할 변경이 없어요', 'No changes to save');
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
  // 고친 행이 없거나 저장하는 중이면 저장·되돌리기 버튼을 잠가요. (React·Vue·Angular 탭의 버튼과 같은 규칙이에요)
  const lock = (count, saving) => {
    for (const id of ['save', 'discard']) {
      const button = document.getElementById(id);
      if (button instanceof HTMLButtonElement)
        button.disabled = count === 0 || saving;
    }
    if (line)
      line.textContent = saving
        ? L('저장하는 중…', 'Saving…')
        : count > 0
          ? L(`저장할 변경 ${count}행`, `${count} rows to save`)
          : L('저장할 변경이 없어요', 'No changes to save');
  };
  lock(0, false);
  const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
  return () => {
    off();
    line?.remove();
    line = null;
  };
}
export const actions = {
  // 첫 행의 월급을 -1로 만들어서, 서버가 거절하는 경우를 볼 수 있어요.
  makeBad: (api) => {
    const row = api.getRows()[0];
    if (row)
      api.updateRows([{ ...row, salary: -1 }]);
    say({
      ko: '첫 행의 월급을 -1로 바꿨어요 (저장하면 서버가 거절해요)',
      en: 'Changed the pay of the first row to -1 (the server rejects it on save)',
    });
  },
  raise: (api) => {
    const row = api.getRows()[1];
    if (row)
      api.updateRows([{ ...row, salary: row.salary + 10 }]);
  },
  save: async (api) => {
    const report = await api.save();
    say({
      ko: `저장 결과: ${SAVE_WORDS[report.status] ?? '확인이 필요해요'}`,
      en: `Save result: ${SAVE_WORDS_EN[report.status] ?? 'Needs checking'}`,
    });
  },
  discard: (api) => api.rollbackChanges(),
};

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="raise">Raise the second salary by 10</button>
    <button type="button" id="makeBad">Make the first salary -1</button>
    <button type="button" id="save">Save</button>
    <button type="button" id="discard">Discard</button>
  </div>
  <div id="grid" style="height: 440px"></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('raise').addEventListener('click', () => actions.raise(api));
document.getElementById('makeBad').addEventListener('click', () => actions.makeBad(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
/** Pretends to save to a server. It finishes after 0.5 seconds and rejects rows whose pay is below 0. */
export const saveToServer = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 500));
  const failed = changes
    .filter((c) => c.state !== 'removed' && c.row.salary < 0)
    .map((c) => ({
    key: c.key,
    message: 'Pay cannot be less than 0',
  }));
  return { failed };
};
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 130, editable: true, validation: { required: true } },
    { id: 'dept', title: 'Department', width: 120, editable: true },
    {
      id: 'salary',
      title: 'Monthly pay ($100)',
      kind: 'number',
      width: 150,
      align: 'end',
      editable: true,
    },
  ],
  rows: [
    { id: 1, name: 'Liam Carter', dept: 'Dev', salary: 520 },
    { id: 2, name: 'Emma Stone', dept: 'Design', salary: 480 },
    { id: 3, name: 'Noah Reed', dept: 'Sales', salary: 450 },
  ],
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: saveToServer,
};
/** Words that explain the save result. */
export const SAVE_WORDS = {
  saved: 'All saved',
  partial: 'Partly saved',
  failed: 'Could not save',
  invalid: 'Not saved because a value needs fixing',
  empty: 'No changes to save',
};
// This screen (JavaScript version): show the changed count and the saving state in one line above the table.
let line = null;
let say = () => { };
export function setup(api, log) {
  say = log;
  line = document.createElement('div');
  line.style.cssText = 'font-size: 13px; color: var(--muted); margin: 0 0 8px;';
  line.textContent = 'No changes to save';
  document.querySelector('.toolbar')?.insertAdjacentElement('afterend', line);
  // Lock the save and discard buttons when no row is changed or while saving. (Same rule as the buttons in the React, Vue and Angular tabs)
  const lock = (count, saving) => {
    for (const id of ['save', 'discard']) {
      const button = document.getElementById(id);
      if (button instanceof HTMLButtonElement)
        button.disabled = count === 0 || saving;
    }
    if (line)
      line.textContent = saving
        ? 'Saving…'
        : count > 0
          ? `${count} rows to save`
          : 'No changes to save';
  };
  lock(0, false);
  const off = api.on('changesCountChanged', ({ count, saving }) => lock(count, saving));
  return () => {
    off();
    line?.remove();
    line = null;
  };
}
export const actions = {
  // Make the first row's pay -1 so you can see the case where the server rejects it.
  makeBad: (api) => {
    const row = api.getRows()[0];
    if (row)
      api.updateRows([{ ...row, salary: -1 }]);
    say('Changed the pay of the first row to -1 (the server rejects it on save)');
  },
  raise: (api) => {
    const row = api.getRows()[1];
    if (row)
      api.updateRows([{ ...row, salary: row.salary + 10 }]);
  },
  save: async (api) => {
    const report = await api.save();
    say(`Save result: ${SAVE_WORDS[report.status] ?? 'Needs checking'}`);
  },
  discard: (api) => api.rollbackChanges(),
};