이러한 객체로 이루어진 배열 data 가 있을 때, 이것의 JSON형태로 볼 수 있는 Viewer를 웹에 띄울려고 했다.
뷰어는 데이터를 직접적으로 편집 가능 할 수 있게 하는 것이 목표.
뷰어는 데이터의 편집까지 가능하므로 곧 에디터 역할을 함.
두가가지 방식을 생각해봄.
위의 객체를 items 라고 명명했을 때,
1. 아래와 같이 pre 태그 안에 input 박스를 넣어서 key값에 대한 value만 조작 가능하게 만들기
this.$primeEditor.innerHTML = `
<pre>
[
${this.state.items
.map(
(node, idx) => `
{
"id": <input class="EditInput id" data-id=${idx} value=${node.id} type="number" />
"value": <input class="EditInput value" data-id=${idx} value=${node.value} type="number" />
},
`
)
.join('')}
]
</pre>
`;
// 이것은 json 편집기라기엔 의미가 없다 생각해서 폐기
2. 두 번째 방식은 textarea 안에 JSON.stringfy(items)를 넣어준 뒤, 이 후 컨펌을 받을 때 try catch를 통해
변경 된 데이터에 대해
1) JSON 형태를 유지하는지
2) key값 변화는 없는지
3) key- id 의 중복 된 값은 없는지 를 체크함
this.$primeEditor.innerHTML = `
<textarea id="editorTextArea" cols="91" rows=${this.state.items.length * 6}>
${JSON.stringify(this.state.items, null, 4)}
</textarea>
`;
};
this.$target.addEventListener('click', (e) => {
const button = e.target.closest('.ApplyButton');
if (!button) return;
const $editorTextArea = document.querySelector('#editorTextArea');
try {
const newItems = JSON.parse($editorTextArea.value);
if (!isValidate(newItems)) {
return;
}
handleApply(newItems);
} catch (error) {
window.alert('json 형태를 유지해주세요.');
}
});
'FrontEnd > JavaScript' 카테고리의 다른 글
babel 직접 설정해보기 (0) | 2024.04.06 |
---|---|
webpack 직접 설정을 위한 기본 개념 (0) | 2024.04.05 |
[javascript] Custom event (1) | 2023.10.30 |
[JS] url 다루기 (0) | 2023.08.19 |
[자바스크립트] 이터러블 개념과 FE에서의 사용처 (0) | 2023.06.24 |