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

정렬 상태를 코드로 바꾸고 저장해 두기Set and save the sort state from code

정렬 상태는 그냥 목록이에요(어느 컬럼을 어느 방향으로, 우선순위 순서로). 코드로 바로 정해 주고, 지금 정렬을 저장해 두었다가 나중에 그대로 불러올 수 있어요. 저장 위치는 브라우저 저장소나 서버, 저장된 보기 어디든 돼요.The sort state is a plain list of columns and directions in priority order. Set it from code, save the current sort and bring it back later; store it in browser storage, a server or a saved view.

활용Intermediate
직접 써 보기Live preview정렬 상태를 코드로 바꾸고 저장해 두기Set and save the sort state from code

코드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">
    <select aria-label="정렬 설정" id="preset">
      <option value="none" selected>정렬 없음</option>
      <option value="cheapest">가격 싼 순</option>
      <option value="byCategory">분류 → 가격 높은 순</option>
    </select>
    <button type="button" id="save">지금 정렬 저장</button>
    <button type="button" id="restore">저장한 정렬 불러오기</button>
  </div>
  <div id="grid" style="height: 330px"></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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
example.js
export const options = {
  columns: [
    { id: 'name', title: '상품', width: 170 },
    { id: 'category', title: '분류', width: 130 },
    {
      id: 'price',
      title: '가격(원)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('ko-KR'),
    },
  ],
  rows: [
    { id: 1, name: '스탠드 조명', category: '조명', price: 39000 },
    { id: 2, name: '높이조절 책상', category: '가구', price: 520000 },
    { id: 3, name: '모니터 암', category: '액세서리', price: 85000 },
    { id: 4, name: '사무용 의자', category: '가구', price: 310000 },
    { id: 5, name: '케이블 트레이', category: '액세서리', price: 18000 },
    { id: 6, name: '플로어 조명', category: '조명', price: 95000 },
  ],
  rowKey: 'id',
};
// 정렬 상태(sortModel)는 그리드 밖에서도 다룰 수 있어요. 사용자가 고른 정렬을 저장해 두었다가(예: localStorage,
// 저장된 보기) 나중에 setSortModel로 돌려주면 돼요. 아래는 '저장'과 '불러오기'를 직접 해 보는 예제예요.
const PRESETS = {
  none: [],
  cheapest: [{ columnId: 'price', direction: 'asc' }],
  byCategory: [
    { columnId: 'category', direction: 'asc' },
    { columnId: 'price', direction: 'desc' },
  ],
};
let saved = [];
let say = () => { };
const TITLE = { name: '상품', category: '분류', price: '가격' };
const describe = (model, none) => model.length === 0
  ? none
  : model
    .map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
    .join(' → ');
export function setup(api, log) {
  say = log;
  saved = [];
  const off = api.on('sortChanged', ({ sortModel }) => log({
    ko: `지금 정렬: ${describe(sortModel, '정렬 없음')}`,
    en: `Sort now: ${describe(sortModel, 'no sort')}`,
  }));
  return () => off();
}
export const actions = {
  preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
  save: (api) => {
    saved = api.getSortModel();
    say({
      ko: `저장했어요: ${describe(saved, '정렬 없음')}`,
      en: `Saved: ${describe(saved, 'no sort')}`,
    });
  },
  restore: (api) => {
    api.setSortModel(saved);
    say({
      ko: `불러왔어요: ${describe(saved, '정렬 없음')}`,
      en: `Loaded: ${describe(saved, 'no sort')}`,
    });
  },
};

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">
    <select aria-label="Set sort" id="preset">
      <option value="none" selected>No sort</option>
      <option value="cheapest">Cheapest first</option>
      <option value="byCategory">Category, then price descending</option>
    </select>
    <button type="button" id="save">Save current sort</button>
    <button type="button" id="restore">Restore saved sort</button>
  </div>
  <div id="grid" style="height: 330px"></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('preset').addEventListener('change', (event) => actions.preset(api, event.target.value));
document.getElementById('save').addEventListener('click', () => actions.save(api));
document.getElementById('restore').addEventListener('click', () => actions.restore(api));
example.js
export const options = {
  columns: [
    { id: 'name', title: 'Product', width: 170 },
    { id: 'category', title: 'Category', width: 130 },
    {
      id: 'price',
      title: 'Price ($)',
      kind: 'number',
      width: 130,
      align: 'end',
      formatValue: (value) => Number(value).toLocaleString('en-US'),
    },
  ],
  rows: [
    { id: 1, name: 'Desk lamp', category: 'Lighting', price: 39 },
    { id: 2, name: 'Height-adjustable desk', category: 'Furniture', price: 520 },
    { id: 3, name: 'Monitor arm', category: 'Accessories', price: 85 },
    { id: 4, name: 'Office chair', category: 'Furniture', price: 310 },
    { id: 5, name: 'Cable tray', category: 'Accessories', price: 18 },
    { id: 6, name: 'Floor lamp', category: 'Lighting', price: 95 },
  ],
  rowKey: 'id',
};
// The sort state (sortModel) can be handled outside the grid too. Store the sort the user picked (for example in localStorage
// or a saved view) and give it back later with setSortModel. This example lets you try "save" and "load" by hand.
const PRESETS = {
  none: [],
  cheapest: [{ columnId: 'price', direction: 'asc' }],
  byCategory: [
    { columnId: 'category', direction: 'asc' },
    { columnId: 'price', direction: 'desc' },
  ],
};
let saved = [];
let say = () => { };
const TITLE = { name: 'Product', category: 'Category', price: 'Price' };
const describe = (model, none) => model.length === 0
  ? none
  : model
    .map((s) => `${TITLE[s.columnId] ?? s.columnId} ${s.direction === 'asc' ? '▲' : '▼'}`)
    .join(' → ');
export function setup(api, log) {
  say = log;
  saved = [];
  const off = api.on('sortChanged', ({ sortModel }) => log(`Sort now: ${describe(sortModel, 'no sort')}`));
  return () => off();
}
export const actions = {
  preset: (api, value) => api.setSortModel(PRESETS[value ?? 'none'] ?? []),
  save: (api) => {
    saved = api.getSortModel();
    say(`Saved: ${describe(saved, 'no sort')}`);
  },
  restore: (api) => {
    api.setSortModel(saved);
    say(`Loaded: ${describe(saved, 'no sort')}`);
  },
};