创建插件 4.0.0
¥Creating a Plugin 4.0.0
我们为插件提供了轻量级的规范和 API。此功能由我们的默认插件(例如 代码高亮 和 Markdown)使用,但你也可以使用它来创建自己的插件。
¥We provide a lightweight specification and API for plugins. This is used by our default plugins like code highlighting and Markdown but can also be used to create your own plugins.
插件定义
¥Plugin Definition
插件是包含以下属性的对象。
¥Plugins are objects that contain the following properties.
属性 | 值 |
---|---|
id String | 插件唯一 ID。这可用于通过 Reveal.getPlugin(<id>) 检索插件实例。 |
init Function | 一个可选函数,在插件运行时调用。它使用一个参数调用;插件注册的 演示文稿实例 的引用。 init 函数可以选择返回 Promise。如果返回的是 Promise,reveal.js 会等待它解析后,演示文稿才会完成初始化并触发 就绪事件。 |
destroy Function | 当此插件注册到的 reveal.js 实例未初始化时调用的可选函数。 |
以下是一个按下 T 键时会随机播放演示文稿中所有幻灯片的示例插件。请注意,我们导出了一个返回新插件对象的函数。这样做是因为可能存在 同一页面上的多个演示实例,并且每个 同一页面上的多个演示实例 都应该有自己的插件实例。
¥Here's an example plugin which shuffles all slides in a presentation when the T key is pressed. Note that we export a function that returns a new plugin object. This is done because there may be multiple presentation instances on the same page, and each should have their own instance of our plugin.
// toaster.js
export default () => ({
id: 'toaster',
init: (deck) => {
deck.addKeyBinding({ keyCode: 84, key: 'T' }, () => {
deck.shuffle();
console.log('🍻');
});
},
});
注册插件
¥Registering a Plugin
插件的注册方式是将它们包含在 配置选项 的 plugins
数组中。你还可以使用 Reveal.registerPlugin( Plugin )
在运行时注册插件。
¥Plugins are registered by including them in the plugins
array of the config options. You can also register a plugin at runtime using Reveal.registerPlugin( Plugin )
.
import Reveal from 'dist/reveal.esm.js';
import Toaster from 'toaster.js';
Reveal.initialize({
plugins: [Toaster],
});
异步插件
¥Async Plugins
如果你的插件需要在 reveal.js 完成初始化之前运行异步代码,它可以返回一个 Promise。以下是一个将初始化延迟三秒的示例插件。
¥If your plugin needs to run asynchronous code before reveal.js finishes initializing it can return a Promise. Here's an example plugin that will delay initialization for three seconds.
let WaitForIt = {
id: 'wait-for-it',
init: (deck) => {
return new Promise((resolve) => setTimeout(resolve, 3000));
},
};
Reveal.initialize({ plugins: [WaitForIt] }).then(() => {
console.log('Three seconds later...');
});