ckeditor5:编辑器的核心架构

编辑器的核心架构、概念等介绍
更新于: 2021-12-19 12:57:29

插件(Plugins)

  • 在 ckeditor5的架构里,插件是很重要的,知道一切东西
  • 插件是高度细粒度的
  • 插件对编辑器了如指掌
  • 插件应该尽可能少地了解其他插件。

Every feature is implemented or at least enabled by a plugin.
Plugins are highly granular.
Plugins know everything about the editor.
Plugins should know as little about other plugins as possible.

import Plugin from "@ckeditor/ckeditor5-core/src/plugin";
import MyDependency from "some/other/plugin";

class MyPlugin extends Plugin {
  static get requires() {
    return [MyDependency];
  }

  init() {
    // Initialize your plugin here.
    this.editor; // The editor instance which loaded this plugin.
  }
}

命令(Commands)

class MyCommand extends Command {
  execute(message) {
    console.log(message);
  }
}

class MyPlugin extends Plugin {
  init() {
    const editor = this.editor;
    editor.commands.add("myCommand", new MyCommand(editor));
  }
}
// Calling 本质是个 observerble
// will log Foo! to the console.
editor.execute( 'myCommand', 'Foo!' )

与command 配合的有一个 refresh 方法

当对模型应用任何更改时,将自动(通过命令本身)调用此方法。这意味着,当编辑器中发生任何更改时,该命令将自动刷新其自身的状态。

This method is called automatically (by the command itself) when any changes are applied to the model. This means that the command automatically refreshes its own state when anything changes in the editor.

 

The important thing about commands is that every change in their state as well as calling the execute() method fire events (e.g. #set:value and #change:value when you change the #value property and #execute when you execute the command).

class MyCommand extends Command {
  execute(message) {
    console.log(message);
  }

  refresh() {
    const doc = this.editor.document;
    this.value = doc.selection.hasAttribute(this.attributeKey);
    this.isEnabled = doc.schema.checkAttributeInSelection(
      doc.selection,
      this.attributeKey
    );
  }
}

事件和obsreverble

class MyPlugin extends Plugin {
  init() {
    // Make MyPlugin listen to someCommand#execute.
    this.listenTo(someCommand, "execute", () => {
      console.log("someCommand was executed");
    });

    // Make MyPlugin listen to someOtherCommand#execute and block it.
    // You listen with a high priority to block the event before
    // someOtherCommand's execute() method is called.
    this.listenTo(
      someOtherCommand,
      "execute",
      (evt) => {
        evt.stop();
      },
      { priority: "high" }
    );
  }

  // Inherited from Plugin:
  destroy() {
    // Removes all listeners added with this.listenTo();
    this.stopListening();
  }
}