記錄一下日常,封裝CKEditor 5,函數(shù)里每次初始化CKEditor 5 的時候,把editor輸出到全局變量。因為重復(fù)使用初始化,導(dǎo)致全局變量只顯示最后初始化的editor。
要解決這個問題,我們需要確保每次調(diào)用 createEditor 函數(shù)時,都能正確地將新的 editor 實例存儲到一個地方,而且這個地方不會因為重復(fù)調(diào)用而覆蓋之前的實例。我們可以通過以下幾種方法來解決這個問題:
- 使用一個數(shù)組來存儲所有的 editor 實例,每個實例都關(guān)聯(lián)到相應(yīng)的 editorId。
- 使用一個對象,其中 key 是 editorId,value 是對應(yīng)的 editor 實例。
- 使用一個映射(Map),其中 key 是 editorId,value 是對應(yīng)的 editor 實例。
代碼
// 用一個對象來存儲所有編輯器實例
const editors = {};
function createEditor(editorId, content) {
// 檢查編輯器是否已存在
if (editors[editorId]) {
console.error(`id為"${editorId}"的編輯器已存在。`);
return;
}
// 創(chuàng)建新的編輯器實例
ClassicEditor
.create(document.querySelector(`#${editorId}`), {
toolbar: {},
placeholder: content,
})
.catch(error => {
console.error(error);
})
.then(editor => {
// 將編輯器實例存儲到全局對象中
editors[editorId] = editor;
});
}
function setContext(editorId, content) {
// 獲取編輯器實例
const editor = editors[editorId];
if (editor) {
// 設(shè)置編輯器的內(nèi)容
editor.setData(content);
} else {
console.error(`id為"${editorId}"的編輯器不存在。`);
}
}
使用方法
// 初始化第一個編輯器
createEditor('notice1', '請輸入公告內(nèi)容1');
// 初始化第二個編輯器
createEditor('notice2', '請輸入公告內(nèi)容2');
// 設(shè)置第一個編輯器的內(nèi)容
setContext('notice1', '這是第一個編輯器的內(nèi)容');
// 設(shè)置第二個編輯器的內(nèi)容
setContext('notice2', '這是第二個編輯器的內(nèi)容');
//獲取編輯器內(nèi)容
//editors是存儲所有編輯器實例,詳情見上面第一塊第二行帶代碼
const editor = editors['notice1'];
console.log(editor.getData()); //輸出:這是第一個編輯器的內(nèi)容
每次調(diào)用 createEditor 函數(shù)時,都會檢查該 editorId 是否已存在。如果已存在,會打印一個錯誤信息。如果不存在,就會創(chuàng)建一個新的編輯器實例,并將其存儲到 editors 對象中。這樣,即使你多次調(diào)用 createEditor 函數(shù),也不會覆蓋之前的編輯器實例。
同樣地,當(dāng)你調(diào)用 setContext 函數(shù)時,它會檢查 editors 對象中是否存在對應(yīng)的 editor 實例。如果存在,就會更新其內(nèi)容;如果不存在,會打印一個錯誤信息。