> ## Documentation Index
> Fetch the complete documentation index at: https://dev.marginnote.com.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 事件系统

插件面板需要获知 MN 内部发生的事情时，可以通过事件系统接收。事件必须先声明，而后才能在面板中收到来自 MN 的推送。

# 声明事件

事件需要声明后才能被插件接收，否则对其的监听无效。

声明事件需在 `mnaddon.json` 中增加 `events` 字段：

```json mnaddon.json highlight={9} focus={9} theme={null}
{
  "addonid": "mn.hello",
  "title": "你好世界",
  "version": "0.1.0",
  "author": "我",
  "marginnote_version_min": "4.5.0",
  "panel": "index.html",
  "icon": "hello.png",
  "events": ["excerpt", "comments"]
}
```

目前可以声明的事件如下：

* `excerpt`：创建摘录。
  * 返回`{noteid, opened}`。
  * 由于创建摘录时会以 mini 模式唤起所有接收符合条件的事件的面板，所以当唤起成功时 `opened` 为 true，失败或者已经打开面板时为 false
* `comments`：卡片批注有变化（包括折叠展开、新增、修改等）。
  * 返回`{noteid?,noteids}`。
  * 摘录卡片的批注变化时，脑图中的卡片和文档中的标注卡片均会包含在 `noteids` 里，但 `noteid` 仅为被修改的脑图中的卡片
* `practice`：作答纸（整卡截图批注）编辑器关闭。⚠️仅由当前插件打开的作答纸关闭时才可触发。
  * 返回 `{noteid, action, saved, commentId}`
* `synced`：同步合并完成。
  * 无返回值
* `undo`：撤销或重做。
  * 无返回值
* `imported`：卡片被批量添加进学习集。
  * 无返回值

# 监听事件

```javascript theme={null}
mn.on('excerpt', function (d) {
  mn.api('/notes/batch-get', 
    { 
      method: 'POST',
      body: { noteIds: [d.noteid] } }
    ).then(function (r) { render(r); });
});
```

<Warning>
  对于同一事件、同一张卡，在 1.5 秒内的重复事件会被丢弃
</Warning>

<Note>
  页面加载完成之前推来的事件会进入队列，加载完成后会统一发放
</Note>

# 摘录事件筛选

面板关闭时用户进行摘录操作，MN 会先用 `mini` 模式打开面板，再推送摘录事件，事件中的 `opened` 为 `true`。如有需要，可以在完成处理后调用 `mn.close()` 进行关闭。

如果只关心某一类摘录，可以用 `excerptClaim` 进行限制：

```json highlight={15-18} focus={15-18} theme={null}
{
  "addonid": "mn.vocab",
  "author": "MarginNote",
  "title": "Reading Vocabulary",
  "version": "0.13.1",
  "marginnote_version_min": "4.5.0",
  "immersiveOnly": true,
  "panel": "index.html",
  "icon": "vocab2.png",
  "panelWidth": 420,
  "panelMaxHeight": 620,
  "events": [
    "excerpt"
  ],
  "excerptClaim": {
    "hashtag": "#VocabPending",
    "configKey": "pendingTag"
  }
}
```

只有包含 `#VocabPending` 标签的新摘录事件才会触发该插件中的`excerpt`事件。

`configKey` 可选，配置之后此标签可以由模板配置覆盖。如上配置时，取值为模板里 `pluginConfigs["mn.vocab"]["pendingTag"]`。

不写 `excerptClaim` 时，所有摘录行为均会唤起插件面板并触发`excerpt` 事件。

# 卡片菜单命令

`cardCommand` 不需要在 `events` 中声明。用户在卡片菜单里点了声明过的命令之后会触发`cardCommand`事件：

```javascript theme={null}
mn.on('cardCommand', function (d) {
  var commandID = d.id
  var noteID = d.noteID
});
```

卡片命令具体配置参见[卡片与摘录菜单命令](/zh/menu-commands)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.