💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] Quill编辑器的核心优势是有丰富的API和强大的定制能力。当你想在Quill的API上扩展功能时,将其作为一个模块来管理可能会比较方便。在本文中,我将介绍构建一种技术器模块的方法,这是许多文字处理软件的常见功能。 注意:Quill含有特定功能的内置模块,你可以通过实现你自己模块并用相同的名称注册来覆盖这些默认[模块](../模块modules.md)。 ## 文字计数 文字计数器的核心功能就是计算编辑器中的字数,并在通过某些UI显示出来。因此,我们需要: 1. 监听Quill的text-change时间 1. 计算字数 1. 显示结果. 让我们之间展示一恶搞完整的例子! ```js // 实现并注册模块 Quill.register('modules/counter', function(quill, options) { var container = document.querySelector('#counter'); quill.on('text-change', function() { var text = quill.getText(); //用这种方法计算字数有几个问题,我们以后会解决 container.innerText = text.split(/\s+/).length; }); }); // 现在,我们可以像这样初始化Quill var quill = new Quill('#editor', { modules: { counter: true } }); ``` 这样,我们在Quill中添加了一个自定义模块。函数功能可以作为模块[注册](../api.md),并且注册时可以传递相应的Quill对象和任何选项。 ## 使用Options 模块可以传递一个option对象,这个option对象可以用作调整所需的行为。我们可以使用这个来接受显示计数器的容器,而不是硬编码字符串。 下面,我们让计数器实现计算单词或字符的功能: ```js Quill.register('modules/counter', function(quill, options) { var container = document.querySelector(options.container); quill.on('text-change', function() { var text = quill.getText(); if (options.unit === 'word') { container.innerText = text.split(/\s+/).length + ' words'; } else { container.innerText = text.length + ' characters'; } }); }); var quill = new Quill('#editor', { modules: { counter: { container: '#counter', unit: 'word' } } }); ``` ## 构造器(Constructors) 由于任何函数都可以注册为Quill模块,我们可以用ES5 constructor或ES6类来实现计数器功能。 这让我们可以直接访问和使用模块。 ```js var Counter = function(quill, options) { this.quill = quill; this.options = options; var container = document.querySelector(options.container); var _this = this; quill.on('text-change', function() { var length = _this.calculate(); container.innerText = length + ' ' + options.unit + 's'; }); }; Counter.prototype.calculate = function() { var text = this.quill.getText(); if (this.options.unit === 'word') { return text.split(/\s+/).length; } else { return text.length; } }; Quill.register('modules/counter', Counter); var quill = new Quill('#editor', { modules: { counter: { container: '#counter', unit: 'word' } } }); var counter = quill.getModule('counter'); // 我们可以直接访问calculate。 console.log(counter.calculate(), 'words'); ``` ## 打包 现在,我们发布这个ES6模块并且修复一些讨厌的错误。就这样。 ```js class Counter { constructor(quill, options) { this.quill = quill; this.options = options; this.container = document.querySelector(options.container); quill.on('text-change', this.update.bind(this)); this.update(); // 初始化内容 } calculate() { let text = this.quill.getText(); if (this.options.unit === 'word') { text = text.trim(); // Splitting empty text returns a non-empty array return text.length > 0 ? text.split(/\s+/).length : 0; } else { return text.length; } } update() { var length = this.calculate(); var label = this.options.unit; if (length !== 1) { label += 's'; } this.container.innerText = length + ' ' + label; } } Quill.register('modules/counter', Counter); var quill = new Quill('#editor', { modules: { counter: { container: '#counter', unit: 'word' } } }); ```