构建自定义模块
Quill 作为编辑器的核心优势在于其丰富的 API 和强大的定制功能。当你在 Quill 的 API 之上实现功能时,将其组织为模块可能会很方便。在本指南中,我们将介绍一种构建字数统计模块的方法,这是许多文字处理器中常见的功能。
¥Quill's core strength as an editor is its rich API and powerful customization capabilities. As you implement functionality on top of Quill's API, it may be convenient to organize this as a module. For the purpose of this guide, we will walk through one way to build a word counter module, a commonly found feature in many word processors.
Quill 内部模块决定了其功能的组织方式。你可以通过实现自己的 modules 并使用相同的名称注册来覆盖这些默认的 modules。
¥Internally modules are how much of Quill's functionality is organized. You can overwrite these default modules by implementing your own and registering it with the same name.
字数统计
¥Counting Words
字数计数器的核心只是计算编辑器中的字数,并在某些 UI 中显示该值。因此我们需要:
¥At its core a word counter simply counts the number of words in the editor and displays this value in some UI. Thus we need to:
-
在 Quill 中监听文本变化。
¥Listen for text changes in Quill.
-
计算字数。
¥Count the number of words.
-
显示此值。
¥Display this value.
让我们直接看一个完整的示例!
¥Let's jump straight in with a complete example!
<link href="/index.css" rel="stylesheet"> <div id="editor"></div> <div id="counter">0</div> <script src="/index.js"></script>
这就是向 Quill 添加自定义模块所需的全部步骤!一个函数可以作为模块被 registered 使用,它将被传递相应的 Quill 编辑器对象以及所有选项。
¥That's all it takes to add a custom module to Quill! A function can be registered as a module and it will be passed the corresponding Quill editor object along with any options.
使用选项
¥Using Options
模块会传递一个选项对象,可用于微调所需的行为。我们可以用它来接受计数器容器的选择器,而不是硬编码的字符串。让我们自定义计数器,使其计数单词或字符:
¥Modules are passed an options object that can be used to fine tune the desired behavior. We can use this to accept a selector for the counter container instead of a hard-coded string. Let's also customize the counter to either count words or characters:
<link href="/index.css" rel="stylesheet"> <div id="editor"></div> <div id="counter">0</div> <script src="/index.js"></script>
构造函数
¥Constructors
由于任何函数都可以注册为 Quill 模块,因此我们可以将计数器实现为 ES5 构造函数或 ES6 类。这使我们能够直接访问和使用该模块。
¥Since any function can be registered as a Quill module, we could have implemented our counter as an ES5 constructor or ES6 class. This allows us to access and utilize the module directly.
<link href="/index.css" rel="stylesheet"> <div id="editor"></div> <div id="counter">0</div> <script src="/index.js"></script>
总结
¥Wrapping It All Up
现在让我们用 ES6 完善这个模块,并修复一些棘手的 bug。就这些!
¥Now let's polish off the module in ES6 and fix a few pesky bugs. That's all there is to it!
<link href="/index.css" rel="stylesheet"> <div id="editor"></div> <div id="counter">0</div> <script src="/index.js"></script>