[javascript] MediumEditor에서 서로 다른 에디터 사이 데이터 공유하기

MediumEditor는 매우 강력한 텍스트 편집기 라이브러리입니다. 하지만 여러 개의 에디터를 사용하는 경우, 에디터 간에 데이터를 공유하는 것이 어려울 수 있습니다. 이번 블로그 포스트에서는 MediumEditor에서 서로 다른 에디터 사이의 데이터를 공유하는 방법을 알려드리겠습니다.

문제

MediumEditor는 독립적인 텍스트 에디터를 생성하는 데 사용됩니다. 하지만 모든 에디터가 서로 독립적이기 때문에, 에디터 간에 데이터를 공유하는 것은 기본적으로 지원되지 않습니다.

해결책

MediumEditor에서 서로 다른 에디터 간에 데이터를 공유하기 위해 다음과 같은 방법을 사용할 수 있습니다.

이벤트 사용하기

MediumEditor는 editableInput이라는 이벤트를 발생시킵니다. 이 이벤트는 에디터에서 텍스트가 입력될 때마다 호출됩니다. 이 이벤트를 활용하여 다른 에디터에 데이터를 전달할 수 있습니다.

const editor1 = new MediumEditor('.editor1');
const editor2 = new MediumEditor('.editor2');

editor1.subscribe('editableInput', function(event, element) {
    const content = editor1.getContent();
    editor2.setContent(content);
});

editor2.subscribe('editableInput', function(event, element) {
    const content = editor2.getContent();
    editor1.setContent(content);
});

위의 코드에서 editor1editableInput 이벤트가 발생하면, 해당 에디터의 내용을 가져와 editor2에 설정합니다. 이와 마찬가지로 editor2editableInput 이벤트가 발생하면, 해당 에디터의 내용을 가져와 editor1에 설정합니다.

중앙 데이터 저장소 사용하기

또 다른 방법은 중앙 데이터 저장소를 사용하는 것입니다. 에디터 간에 데이터를 공유하기 위해 중앙 데이터 저장소를 만들고, 각 에디터에서 데이터를 가져와 저장소에 저장하고 불러오는 방식입니다.

const dataStore = {};

const editor1 = new MediumEditor('.editor1');
const editor2 = new MediumEditor('.editor2');

editor1.subscribe('editableInput', function(event, element) {
    const content = editor1.getContent();
    dataStore.editor1 = content;
    editor2.setContent(content);
});

editor2.subscribe('editableInput', function(event, element) {
    const content = editor2.getContent();
    dataStore.editor2 = content;
    editor1.setContent(content);
});

위의 코드에서 dataStore라는 객체를 사용하여 데이터를 저장합니다. editor1에서 editableInput 이벤트가 발생하면 해당 내용을 dataStore.editor1에 저장하고, editor2의 내용에 설정합니다. 마찬가지로 editor2에서 editableInput 이벤트가 발생하면 해당 내용을 dataStore.editor2에 저장하고, editor1의 내용에 설정합니다.

결론

MediumEditor에서 서로 다른 에디터 사이의 데이터를 공유하는 것은 가능합니다. 이번 블로그 포스트에서는 이벤트 및 중앙 데이터 저장소를 활용하여 데이터를 공유하는 방법을 소개했습니다. 이를 통해 여러 개의 에디터를 사용할 때 효율적으로 데이터를 공유할 수 있습니다.