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

저장하지 않았으면 떠나기 전에 경고하기Warn before leaving with unsaved changes

저장하지 않은 수정이 있을 때만, 탭을 닫거나 새로고침하려 하면 브라우저가 한 번 더 물어봐요. 수정이 없으면 그냥 떠나요. 화면이 사라질 때는 이 경고도 함께 걷어 내야 해요.Only when there are unsaved edits does the browser ask once more before the tab is closed or reloaded. With no edits you leave silently. The warning must be removed when the screen goes away.

활용Intermediate
직접 써 보기Live preview저장하지 않았으면 떠나기 전에 경고하기Warn before leaving with unsaved changes

코드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="markSaved">저장한 것으로 처리</button>
    <button type="button" id="discard">되돌리기</button>
  </div>
  <div id="grid" style="height: 290px"></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('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const items = ['A4 용지', '볼펜 세트', '포스트잇', '스테이플러', '노트'];
export const options = {
  columns: [
    { id: 'item', title: '품목', width: 180, editable: true },
    {
      id: 'quantity',
      title: '수량',
      kind: 'number',
      width: 110,
      editable: true,
      validation: { min: 0 },
    },
  ],
  rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
  rowKey: 'id',
};
// '떠날 때 묻기'는 그리드 밖의 window에 걸어요. 이 화면이 사라질 때 꼭 풀어 주지 않으면 화면이 없어진 뒤에도
// 계속 남아요. 저장하지 않은 변경이 있으면 브라우저가 떠나기 전에 한 번 물어요.
export function setup(api, log) {
  const warn = (event) => {
    if (api.hasChanges())
      event.preventDefault();
  };
  window.addEventListener('beforeunload', warn);
  log({
    ko: '표의 값을 고쳐 보세요. 저장하지 않은 변경이 있으면 창을 닫을 때 브라우저가 물어요',
    en: 'Edit a value in the table. With unsaved changes, the browser asks when you close the window',
  });
  const off = api.on('changesCountChanged', (e) => log({
    ko: e.count > 0
      ? `저장하지 않은 변경 ${e.count}개 — 지금 떠나면 브라우저가 물어요`
      : '저장하지 않은 변경이 없어요',
    en: e.count > 0
      ? `${e.count} unsaved changes — the browser asks if you leave now`
      : 'No unsaved changes',
  }));
  return () => {
    window.removeEventListener('beforeunload', warn);
    off();
  };
}
export const actions = {
  markSaved: (api) => api.commitChanges(),
  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="markSaved">Mark as saved</button>
    <button type="button" id="discard">Discard</button>
  </div>
  <div id="grid" style="height: 290px"></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('markSaved').addEventListener('click', () => actions.markSaved(api));
document.getElementById('discard').addEventListener('click', () => actions.discard(api));
example.js
const items = ['A4 paper', 'Ballpoint pens', 'Sticky notes', 'Stapler', 'Notebook'];
export const options = {
  columns: [
    { id: 'item', title: 'Item', width: 180, editable: true },
    {
      id: 'quantity',
      title: 'Quantity',
      kind: 'number',
      width: 110,
      editable: true,
      validation: { min: 0 },
    },
  ],
  rows: items.map((item, i) => ({ id: i + 1, item, quantity: 10 + i * 5 })),
  rowKey: 'id',
};
// 'Ask when leaving' is attached to the window outside the grid. If you do not remove it when this screen goes away, it
// stays even after the screen is gone. With unsaved changes, the browser asks once before leaving.
export function setup(api, log) {
  const warn = (event) => {
    if (api.hasChanges())
      event.preventDefault();
  };
  window.addEventListener('beforeunload', warn);
  log('Edit a value in the table. With unsaved changes, the browser asks when you close the window');
  const off = api.on('changesCountChanged', (e) => log(e.count > 0
    ? `${e.count} unsaved changes — the browser asks if you leave now`
    : 'No unsaved changes'));
  return () => {
    window.removeEventListener('beforeunload', warn);
    off();
  };
}
export const actions = {
  markSaved: (api) => api.commitChanges(),
  discard: (api) => api.rollbackChanges(),
};