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

저장 전에는 정렬·쪽 이동 막기Block sorting and paging before saving

hooks.beforeSort, beforeFilter, beforePageChange가 false를 돌려주면 그 조작은 취소돼요. 이 예제는 저장하지 않은 고침(hasChanges)이 있는 동안 정렬·필터·쪽 이동을 막아 고친 줄이 사라지거나 흩어지지 않게 해요. 훅의 source로 화면 조작과 코드 호출을 구분해요.When hooks.beforeSort, beforeFilter or beforePageChange returns false, that action is cancelled. This example blocks sorting, filtering and page changes while there are unsaved edits (hasChanges) so edited rows do not scatter. The hook source tells a gesture from a code call.

활용Intermediate
직접 써 보기Live preview저장 전에는 정렬·쪽 이동 막기Block sorting and paging before saving

코드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="sort">코드로 정렬하기</button>
    <button type="button" id="next">다음 쪽(코드)</button>
    <button type="button" id="save">저장하기</button>
  </div>
  <div id="grid" style="height: 230px"></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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
const en = document.documentElement.dataset.lang === 'en';
const names = en
  ? ['Alex', 'Blair', 'Casey', 'Drew', 'Emery', 'Finn', 'Gray', 'Harper', 'Indy', 'Jordan']
  : [
    '김서연',
    '이준호',
    '박민지',
    '최도윤',
    '정하은',
    '한지우',
    '오세훈',
    '윤아름',
    '강태양',
    '서하늘',
  ];
const teams = en ? ['Dev', 'Design', 'Ops'] : ['개발', '디자인', '운영'];
let say = () => { };
let apiRef = null;
/** 저장하지 않은 고침이 있으면 막고 이유를 기록해요. 막힌 조작은 이벤트도 상태 변화도 없어요. */
const guard = (what) => (ctx) => {
  if (apiRef?.hasChanges() !== true)
    return;
  say({
    ko: `저장하지 않은 고침이 있어 ${what.ko}을(를) 막았어요 (${ctx.source === 'user' ? '화면 조작' : '코드 호출'})`,
    en: `Blocked the ${what.en}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`,
  });
  return false;
};
export const options = {
  columns: [
    { id: 'name', title: en ? 'Name' : '이름', width: 120, editable: true, sortable: true },
    { id: 'team', title: en ? 'Team' : '팀', width: 100, sortable: true },
    {
      id: 'score',
      title: en ? 'Score' : '점수',
      kind: 'number',
      width: 90,
      editable: true,
      sortable: true,
    },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    team: teams[i % 3],
    score: 60 + ((i * 7) % 40),
  })),
  rowKey: 'id',
  saveMode: 'batch',
  pagination: { mode: 'client', pageSize: 5 },
  hooks: {
    beforeSort: guard({ ko: '정렬', en: 'sort' }),
    beforeFilter: guard({ ko: '필터', en: 'filter' }),
    beforePageChange: guard({ ko: '쪽 이동', en: 'page change' }),
  },
};
export function setup(api, log) {
  say = log;
  apiRef = api;
  return () => {
    apiRef = null;
  };
}
export const actions = {
  save: (api) => {
    api.commitChanges();
    say({
      ko: '저장했어요. 이제 정렬·쪽 이동이 풀려요.',
      en: 'Saved. Sorting and paging work again.',
    });
  },
  sort: (api) => {
    api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
  },
  next: (api) => api.setPage(api.getPage() + 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="sort">Sort from code</button>
    <button type="button" id="next">Next page (code)</button>
    <button type="button" id="save">Save</button>
  </div>
  <div id="grid" style="height: 230px"></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('sort').addEventListener('click', () => actions.sort(api));
document.getElementById('next').addEventListener('click', () => actions.next(api));
document.getElementById('save').addEventListener('click', () => actions.save(api));
example.js
const names = [
  'Liam Carter',
  'Emma Stone',
  'Noah Kim',
  'Olivia Reed',
  'Ava Brooks',
  'Mason Lee',
  'Sophia Hayes',
  'Ethan Cole',
  'Isabella Ward',
  'Lucas Young',
];
const teams = ['Dev', 'Design', 'Ops'];
let say = () => { };
let apiRef = null;
/** Blocks the action and logs the reason while there are unsaved edits. A blocked action fires no event and changes no state. */
const guard = (what) => (ctx) => {
  if (apiRef?.hasChanges() !== true)
    return;
  say(`Blocked the ${what}: there are unsaved edits (${ctx.source === 'user' ? 'gesture' : 'code call'})`);
  return false;
};
export const options = {
  columns: [
    { id: 'name', title: 'Name', width: 120, editable: true, sortable: true },
    { id: 'team', title: 'Team', width: 100, sortable: true },
    {
      id: 'score',
      title: 'Score',
      kind: 'number',
      width: 90,
      editable: true,
      sortable: true,
    },
  ],
  rows: names.map((name, i) => ({
    id: i + 1,
    name,
    team: teams[i % 3],
    score: 60 + ((i * 7) % 40),
  })),
  rowKey: 'id',
  saveMode: 'batch',
  pagination: { mode: 'client', pageSize: 5 },
  hooks: {
    beforeSort: guard('sort'),
    beforeFilter: guard('filter'),
    beforePageChange: guard('page change'),
  },
};
export function setup(api, log) {
  say = log;
  apiRef = api;
  return () => {
    apiRef = null;
  };
}
export const actions = {
  save: (api) => {
    api.commitChanges();
    say('Saved. Sorting and paging work again.');
  },
  sort: (api) => {
    api.setSortModel([{ columnId: 'score', direction: 'desc' }]);
  },
  next: (api) => api.setPage(api.getPage() + 1),
};