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

여러 페이지에서 고친 것을 한 번에 저장Save edits from several pages at once

일괄 저장 모드에서는 고친 값이 모아 두어서, 페이지를 넘겨도 사라지지 않아요. 저장 버튼을 한 번 누르면 모든 페이지에서 고친 행이 함께 서버로 가요.In batch save mode edits are collected, so changing page does not lose them. One save sends the rows edited on every page together.

심화Advanced
직접 써 보기Live preview여러 페이지에서 고친 것을 한 번에 저장Save edits from several pages at once

코드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="editOnThisPage">이 페이지 첫 행 고치기</button>
    <button type="button" id="nextPage">다음 페이지</button>
    <button type="button" id="save">저장</button>
  </div>
  <div id="grid" style="height: 500px"></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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
let say = () => { };
// 서버에 저장하는 척하는 핸들러예요. 결과 없이 끝나면 모든 행이 저장된 거예요.
const saveToServer = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 400));
  say({
    ko: `서버에 ${changes.length}행을 저장했어요`,
    en: `Saved ${changes.length} rows to the server`,
  });
};
const names = ['김민준', '이서연', '박지호', '최유나', '정도윤', '한소희', '오세훈', '김서윤'];
export const options = {
  columns: [
    { id: 'name', title: '이름', width: 150, editable: true, validation: { required: true } },
    {
      id: 'salary',
      title: '월급(만원)',
      kind: 'number',
      width: 130,
      align: 'end',
      editable: true,
    },
  ],
  rows: Array.from({ length: 40 }, (_, i) => ({
    id: i + 1,
    name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
    salary: 320 + i * 5,
  })),
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: saveToServer,
  pagination: { mode: 'client', pageSize: 10 },
};
// 다른 페이지에서 고친 값도 페이지를 넘겨도 사라지지 않고, 저장 한 번에 모두 서버로 가요.
export function setup(api, log) {
  say = log;
  return api.on('changesCountChanged', ({ count, modified, saving }) => {
    log({
      ko: `저장 대기 ${count}행 (수정 ${modified}) · ${api.getPage()}페이지${saving ? ' · 저장 중…' : ''}`,
      en: `${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`,
    });
  });
}
export const actions = {
  // 지금 페이지 첫 행의 월급을 10만원 올려요(직접 셀을 두 번 눌러 고쳐도 같아요).
  editOnThisPage: (api) => {
    const row = api.getVisibleRows()[0];
    if (row)
      api.updateRows([{ ...row, salary: row.salary + 10 }]);
  },
  nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
  save: async (api) => {
    const report = await api.save();
    const words = {
      saved: ['모두 저장됐어요', 'All saved'],
      empty: ['저장할 변경이 없어요', 'No changes to save'],
    };
    const word = words[report.status] ?? [
      '일부는 저장하지 못했어요',
      'Some rows could not be saved',
    ];
    say({ ko: `저장 결과: ${word[0]}`, en: `Save result: ${word[1]}` });
  },
};

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="editOnThisPage">Edit first row on this page</button>
    <button type="button" id="nextPage">Next page</button>
    <button type="button" id="save">Save</button>
  </div>
  <div id="grid" style="height: 500px"></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('editOnThisPage').addEventListener('click', () => actions.editOnThisPage(api));
document.getElementById('nextPage').addEventListener('click', () => actions.nextPage(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
let say = () => { };
// A handler that pretends to save to a server. If it finishes without a result, every row counts as saved.
const saveToServer = async (changes) => {
  await new Promise((resolve) => setTimeout(resolve, 400));
  say(`Saved ${changes.length} rows to the server`);
};
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Kim',
  'Olivia Park',
  'Ethan Brown',
  'Mia Johnson',
  'Jack Miller',
  'Ava Davis',
];
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 170, editable: true, validation: { required: true } },
    {
      id: 'salary',
      title: 'Monthly pay ($)',
      kind: 'number',
      width: 180,
      align: 'end',
      editable: true,
    },
  ],
  rows: Array.from({ length: 40 }, (_, i) => ({
    id: i + 1,
    name: `${names[i % 8]}${i >= 8 ? ` ${Math.floor(i / 8) + 1}` : ''}`,
    salary: 3200 + i * 50,
  })),
  rowKey: 'id',
  saveMode: 'batch',
  saveHandler: saveToServer,
  pagination: { mode: 'client', pageSize: 10 },
};
// Values edited on other pages do not disappear when you change pages, and one save sends them all to the server.
export function setup(api, log) {
  say = log;
  return api.on('changesCountChanged', ({ count, modified, saving }) => {
    log(`${count} rows waiting to save (${modified} modified) · page ${api.getPage()}${saving ? ' · saving…' : ''}`);
  });
}
export const actions = {
  // Raise the pay of the first row on this page by 100 (editing the cell by hand gives the same result).
  editOnThisPage: (api) => {
    const row = api.getVisibleRows()[0];
    if (row)
      api.updateRows([{ ...row, salary: row.salary + 100 }]);
  },
  nextPage: (api) => api.setPage(Math.min(api.getPage() + 1, api.getPageCount())),
  save: async (api) => {
    const report = await api.save();
    const words = {
      saved: 'All saved',
      empty: 'No changes to save',
    };
    const word = words[report.status] ?? 'Some rows could not be saved';
    say(`Save result: ${word}`);
  },
};