CKEditor5——Plugin理解

今天开始理解学习CK5的插件类,整个类是所有插件的抽象,看看源码:
export default class Plugin {
/**
* @inheritDoc
*/
constructor( editor ) {
this.editor = editor;
this.set( 'isEnabled', true );
/**
* Holds identifiers for {@link #forceDisabled} mechanism.
*
* @type {Set.<String>}
* @private
*/
this._disableStack = new Set();
}
}
从以上代码可以看出,每个插件有包含一个eidtor引用,因此,插件可以调用编辑器实例的任何方法,包括调用命令,判断editor的只读性等等。
这里有一个isEnabled
属性,判断当前插件是否可用,以及一个设置插件可用性的Set集合。
插件的启用和禁用
然后再看看另外另个重要方法:
forceDisabled( id ) {
this._disableStack.add( id );
if ( this._disableStack.size == 1 ) {
this.on( 'set:isEnabled', forceDisable, { priority: 'highest' } );
this.isEnabled = false;
}
}
/**
* Clears forced disable previously set through {@link #forceDisabled}. See {@link #forceDisabled}.
*
* @param {String} id Unique identifier, equal to the one passed in {@link #forceDisabled} call.
*/
clearForceDisabled( id ) {
this._disableStack.delete( id );
if ( this._disableStack.size == 0 ) {
this.off( 'set:isEnabled', forceDisable );
this.isEnabled = true;
}
}
这里如果需要禁用插件,只需要调用forceDisabled
方法,这个方法很简单,就是将名字存储起来,然后绑定一个禁用的事件set:isEnabled
,然后设置isEnabled
为false。
同理,清除禁用就是将名字删除掉,并且全部删除掉,然后去掉绑定的set:isEnabled
事件,设置isEnabled
为true。
我们看看这个函数forceDisable
:
function forceDisable( evt ) {
evt.return = false;
evt.stop();
}
看到了吧,一旦我们禁用了插件,当我们再设置plugin.isEnabled
的时候,就会触发这个回调函数,返回值为false,且停止后续回调函数的执行,因为这个优先级是最高,因此插件的这个属性值永远不会修改,它永远是false,因此这个插件永远不可用。当去掉这个事件监听后,这个属性isEnabled
变回true,因此插件又变成可用啦。
大家应该理解这个原理了吧。