我创建了一个自定义插件,如图所示。我可以添加带有“占位符”类的对象。
<span class="placeholder">Loop-ANS(Q2)</span>
.
内联小部件创建自 创建于
内联小部件演示 演示
现在,当有人从编辑器中删除它时,我需要生成一个事件(调用函数),以便我可以标记该项目已在我的 redux 状态中删除。我用下面的代码找到了解决方案。
editor.model.document.on( 'change:data', () => { // Listen to all changes in model.
// Get changes buffered in Differ. Include items moved to the graveyard (removed from document).
const changes = editor.model.document.differ.getChanges( { includeChangesInGraveyard: true } );
for ( const change of changes ) {
// Check items moved to the graveyard (so they are removed from the document root).
if ( change.type == 'insert' && change.name != '$text' && change.position.root.rootName == '$graveyard' ) {
// The element that we are looking for could be nested in some block-quote or a table cell
// so we need to walk through the whole element content and check if our element was removed or not.
const range = editor.model.createRangeOn( change.position.nodeAfter );
for ( const item of range.getItems() ) {
if ( item.is( 'element', 'imageInline' ) ) { // Here you change the value to your element's name.
console.log( 'inline image removed', item ); // (**I will add a callback here**)
}
}
}
}
} );
问题是,当我尝试拖放内联小部件时,它也被视为已删除。即,该元素正在移动到墓地,而这是不应该的。 有什么办法可以防止这种情况吗?当拖放到其他位置时,占位符不会在墓地上移动。或者检查是否因拖放而生成事件而不调用回调。
如果不可能,有什么方法可以停止内联小部件的拖放事件
如果以后有人需要这个功能,可以参考这个代码:
function _getPlaceholderChanges(editor, inGraveyard) {
const changes = editor.model.document.differ.getChanges({
includeChangesInGraveyard: inGraveyard,
});
let changedItems = [];
for (const change of changes) {
if (
inGraveyard
? change.type == "insert" &&
change.name != "$text" &&
change.position.root.rootName == "$graveyard"
: change.type == "insert" && change.name != "$text"
) {
const range = editor.model.createRangeOn(change.position.nodeAfter);
for (const item of range.getItems()) {
if (item.is("element", "placeholder")) {
changedItems.push(item);
}
}
}
}
const changedPlaceholders = changedItems.map((item) =>
item._attrs.get("name")
);
return changedPlaceholders;
}
function placeholderDeletionChecker(editor, questionId, callback) {
const model = editor.model;
model.document.on("change:data", () => {
// Get changes buffered in Differ. Include items moved to the graveyard (removed from document).
const removedPlaceHolders = _getPlaceholderChanges(editor, true);
const addedPlaceHolders = _getPlaceholderChanges(editor, false);
//if a placeholder deleted and added on same time means, this is happend due to reposition of item (drag and drop).
//In this case we wont call the callback
if (removedPlaceHolders.length && !addedPlaceHolders.length) {
callback(questionId, removedPlaceHolders);
}
});
}
export default placeholderDeletionChecker;