事件
ComPDFKit 引擎使用自定义 EventBus 进行跨模块通信。UI 层监听引擎事件以保持状态同步,并通过 addEvent / removeEvent 让集成方响应相同事件。
EventBus
引擎的 EventBus 通过 core 桥接层暴露:
instance.Core.eventBus(); // 引擎的事件总线
instance.Core.addEvent(name, handler);
instance.Core.removeEvent(name, handler);桥接层中的 eventBus.js 是一个薄访问器——返回 core.getDocumentViewer().eventBus,暴露引擎自身的总线,本身不持有状态。
常见引擎事件
| 事件 | 触发时机 |
|---|---|
annotationSelected / annotationDeselected | 批注被选中/取消选中。 |
annotationChanged | 批注被添加/修改/删除。 |
toolChanged | 活动工具变化。 |
toolModeChanged | 工具模式变化。 |
scalechanging | 缩放比例变化。 |
pagerendered | 页面渲染完成。 |
documentloaded | 文档加载完成。 |
onPagesUpdated | 页面更新(同步书签、页数、当前页、缩放、滚动/分页模式)。 |
openAnnotationReply | 打开批注回复线程。 |
updateAnnotationPermission | 批注权限变化。 |
contentEditHistoryChanged / historyChanged | 内容编辑/通用历史变化(驱动撤销/重做标志)。 |
changeRightPanelBtnDisabled | 右面板按钮禁用状态变化。 |
presentationmodechanged | 演示模式切换。 |
UI 如何监听
组件在其 setup/mount 生命周期中注册监听器。例如,DocumentContainer.vue 在 initViewer() 期间注册 updateAnnotationPermission、toolModeChanged、toolChanged、annotationSelected/annotationDeselected、openAnnotationReply、onPagesUpdated、annotationChanged 和 documentloaded。
createHeaderItemsListener(components/HeaderItems/HeaderItemsListener.js)监听 activeTool 和 selectedAnnotation 以重新计算四个属性面板按钮的禁用标志,并订阅 annotationSelected、annotationDeselected、changeRightPanelBtnDisabled 和 presentationmodechanged。
useHistoryListener 将 contentEditHistoryChanged / historyChanged 桥接到 useDocument.setCanUndo / setCanRedo。
生命周期说明:
helpers/hooks/useOnAnnotationPopupOpen.js注册了annotationSelected/annotationDeselected,并通过onScopeDispose移除,使监听器在所属作用域(组件 setup 或effectScope)销毁时清理。当你自行通过core.addEvent注册监听器时,请参照此做法,在onUnmounted(或onScopeDispose)中移除,以避免泄漏。
示例
监听文档加载
instance.Core.addEvent('documentloaded', () => {
console.log('Document loaded');
});监听批注变化
const handler = (annotations, type) => {
console.log('annotations', type, annotations);
};
instance.Core.addEvent('annotationChanged', handler);
// 之后
instance.Core.removeEvent('annotationChanged', handler);监听工具变化
instance.Core.addEvent('toolChanged', (toolName) => {
console.log('Active tool:', toolName);
});viewer 加载握手
除引擎事件外,iframe↔父窗口握手使用 postMessage:
- UI 就绪时 iframe 向
window.parent发送{ type: 'viewerLoaded', docId }(App/index.vueonMounted)。 webviewer.js监听它,捕获iframe.contentWindow.instance,在宿主元素上触发readyCustomEvent,并向 iframe 回发{ type: 'viewerLoaded', options }。
集成方可监听宿主元素上的 ready 事件,或直接 await ComPDFKitViewer.init(...),它会在就绪后以 instance 解析。
相关
- 架构 — 启动流程与 EventBus 角色。
- Core 桥接层 —
eventBus、addEvent、removeEvent。 - 辅助函数、Hooks 与常量 —
useOnAnnotationPopupOpen。