Skip to content
文档目录

sdk 与 签章页面的交互

在 sdk 中,sdk 实例与签章页面是通过 sdk 中的 bus 属性进行交互的,bus 是 sdk 中的事件总线,事件列表中列出了 bus 所支持的所有事件。

其中内部调用不建议通过 bus 进行自行调用(不提供安全性保障),其中可以进行使用的为:

  • CURRENT_FILE_CHANGE: 监听当前文件变化(仅当当前文件 id 变化后触发,文件内容由于签章等导致的变化不触发)
  • FILE_LIST_CHANGE:监听当前文件列表发生变化

使用案例

以下两个原生案例展示了上述 event bus 的使用,如在数据驱动型的框架 (Vue/React/Angular) 中使用,按照框架规则更新数据并展示即可。

示例1:当前文件发生变化后更新 select 选框中的选中项

ts
uKeySdkInstance.bus.on('CURRENT_FILE_CHANGE', (file) => {
  // 文件列表 select 框
  const fileSelect = document.getElementById('fileSelect');
  if (!fileSelect) return;
  // 获取 select 所有选项
  const options = fileSelect.getElementsByTagName('option');
  for (let i = 0; i <options.length; i++) {
    const currentOption = options[i];
    // 设置当前选中项
    if (file?.id && currentOption.value === file.id) {
      currentOption.selected = true;
    } else {
      currentOption.selected = false;
    }
  }
});

示例2:当前文件发生变化后更新 select 选框中的 option

ts
uKeySdkInstance.bus.on('FILE_LIST_CHANGE', (fileList) => {
  console.log('监听文件列表', fileList);
  // 获取当前文件
  const currentFile = uKeySdkInstance?.getCurrentDocument() || null;

  // 创建 fragment 用于添加所有 option 元素
  const fragment = document.createDocumentFragment();
  // 根据文件列表生成 option 元素并添加到 fragment
  fileList.forEach((file) => {
    const option = document.createElement('option');
    if (currentFile && currentFile.id === file.id) {
      option.selected = true;
    }
    option.text = file.filename;
    option.value = file.id;
    fragment.appendChild(option);
  });

  // 将 fragment 添加到 select 元素中
  const fileSelect = document.getElementById('fileSelect');
  if (!fileSelect) return;
  fileSelect.innerHTML = '';
  fileSelect.appendChild(fragment);

  // 监听 select 元素 change 事件,更新当前展示的文件
  if (!fileSelect.onchange) {
    fileSelect.onchange = function (ev: any) {
      const selectedIndex = ev.target.selectedIndex;
      const selectedOption = ev.target[selectedIndex];
      const fileId = selectedOption.value;
      if (fileId) {
        uKeySdkInstance?.doSwitchDocument(fileId);
      }
    };
  }
});