# @collidor/event 中文文档

规范地址：https://npmcn.com/package/%40collidor/event/

版本：4\.7\.2
npm 元数据更新时间：2026-10-08T16:33:23.620Z
中文译文更新时间：2026-11-10T11:09:28.418Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40collidor/event
原文对照：https://npmcn.com/package/%40collidor/event/?lang=original
项目主页：https://github.com/collidor/event#readme
源码仓库：https://github.com/collidor/event

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：829 kB，98 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=24\.0\.0
- 运行依赖：0 个
- 首次发布：2025-02-10T08:29:18.157Z
- 最新版本发布：2026-10-08T16:33:22.816Z
- 近 30 天下载量：7900（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：56（近 12 个月 9 个）

## 中文简介

一个小型的图书馆,用于创建,注册和收听事件.

## 安装

```sh
npm install @collidor/event
```

也可以使用：`pnpm add @collidor/event`、`yarn add @collidor/event`、`bun add @collidor/event`

## README

# @ collidor/ event

[![Codecov](https://codecov.io/gh/collidor/event/branch/main/graph/badge.svg)](https://codecov.io/gh/collidor/event) [![npm version](https://img.shields.io/npm/v/@collidor/event)](https://www.npmjs.com/package/@collidor/event) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

轻量级事件系统 有跨文本通信. 适合现代网络应用,工人,和分布式系统.

* * *

## 安装

```bash
npm install @collidor/event
```

* * *

## 核心特征

-   严格打字的基于类的事件系统
-   跨文本通讯( Window QQ 工人分页)
-   广播频道/共享工作者的内置支持
-   背景传播和中止控制器集成

## 基本用途

### 使用类继承

```ts
import { Event } from "@collidor/event";

class UserUpdate extends Event<{ id: string }> {}
class SystemAlert extends Event<string> {}
```

```ts
import { EventBus } from "@collidor/event";

const bus = new EventBus();

// Subscribe
bus.on(UserUpdate, (data) => {
  console.log(`User ${data.id} updated`);
});

// Publish
bus.emit(new UserUpdate({ id: "123" }));
```

### 使用 `createEvent` (邦德勒/无害安全)

当捆绑用于生产时,JavaScript分解器常常会操纵类名(例如. `class UserUpdate` 变成 `class a`) (中文(简体) ). 自活动总线和频道以来`PortChannel`, (中文(简体) ), `WindowCustomEventPort`(b) 使用其构造器名称对事件进行路线和序列化, `createEvent` 提供了一种类型安全的方法来定义带有固定的,不可忽略的名称的事件 :

```typescript
import { createEvent, EventBus } from "@collidor/event";

// Define event with explicit payload type and name: createEvent<PayloadType>("EventName")
export const UserUpdate = createEvent<{ id: string }>("UserUpdate");

// Void events (no arguments required):
export const UserLoggedOut = createEvent<void>("UserLoggedOut");

const bus = new EventBus();

bus.on(UserUpdate, (data) => {
  console.log(`User ${data.id} updated`);
});

bus.on(UserLoggedOut, () => {
  console.log("User logged out");
});

bus.emit(new UserUpdate({ id: "123" }));
bus.emit(new UserLoggedOut());
```

* * *

## 交叉连接模式

PortChannel 是主要导出通道, 它接受 `MessagePortLike` 端口,该端口 有个 `postMessage` 方法,并可以设置和使用 `onmessage` 属性召回。 这意味着 浏览器的 API 如 BroadcastChannel、 Worker 和 共享 Worker 默认工作 .

我的计划是稍后再加入适配器,这样其他的东西可以像端口一样表现,比如Websockets,WebRTC,Http+SEE和Datagrams.

PortChannel不会向没有发送消息的端口发送事件,首先告诉它有这样的事件的订阅者.

### 1\. 广播频道(对台)

```ts
import { PortChannel, EventBus } from "@collidor/event";

const channel = new PortChannel();
const bus = new EventBus({ channel });
channel.addPort(new BroadcastChannel("app-channel"));

class TabMessage extends Event<string> {}
bus.emit(new TabMessage("Hello from Tab A!"));
```

```ts
import { PortChannel, EventBus } from "@collidor/event";

const channel = new PortChannel();
const bus = new EventBus({ channel });
channel.addPort(new BroadcastChannel("app-channel"));

bus.on(TabMessage, (msg) => {
  console.log("Received:", msg); // "Hello from Tab A!"
});
```

* * *

### 2\. 共享工人(多文本)

```ts
import { PortChannel, EventBus } from "@collidor/event";

const channel = new PortChannel();
const bus = new EventBus({ channel });
const worker = new SharedWorker("worker.js");

channel.addPort(worker.port);

class TaskEvent extends Event<{ id: string }> {}
bus.emit(new TaskEvent({ id: "shared-task" }));
```

```ts
import { PortChannel, EventBus } from "@collidor/event";

const channel = new PortChannel();
const bus = new EventBus({ channel });

// Handle new connections
self.onconnect = (event) => {
  const port = event.ports[0];
  channel.addPort(port);
};

self.start();

bus.on(TaskEvent, ({ id }) => {
  console.log("Processing shared task:", id);
});
```

* * *

## 高级图案

### 背景宣传

```ts
const bus = new EventBus({
  context: { requestId: "123" }
});

bus.on(DataEvent, (data, ctx) => {
  console.log(ctx.requestId); // "123"
});

// Override per emission
bus.emit(new DataEvent(), { requestId: "temp" });
```

* * *

## API 概览

### 事件窗口

-   `on(event, handler, signal?)`
-   `off(event, handler)`
-   `emit(event, context?)`
-   `emitByName(name, data, context?)`

### 端口通道

-   `addPort(port)`
-   `removePort(port)`
-   `publish(event)`
-   `subscribe(name, callback)`
-   `unsubscribe(name, callback)`

#### PortChannel 序列图

```mermaid
sequenceDiagram
    participant S as Server PortChannel
    participant MP as MessagePort
    participant C as Client PortChannel

    %% Server adds a MessagePort (acts as connecting port)
    S->>MP: addPort(port)
    Note over S,MP: Server attaches MessagePort

    %% MessagePort forwards startEvent to the Client
    MP->>C: onmessage({type: "startEvent"})
    Note over C: Client receives startEvent and sets up message handlers

    %% Client subscribes to "TestEvent"
    C->>MP: postMessage({type:"subscribeEvent", name:"TestEvent"})
    Note over C: Client tells that it has a subscription for "TestEvent"

    %% MessagePort delivers subscribeEvent to Server
    MP->>S: onmessage({type:"subscribeEvent", name:"TestEvent"})
    Note over S: Server calls addPortSubscription("TestEvent")

    %% If the Server had buffered events for "TestEvent", flush them:
    alt Buffered events exist for "TestEvent"
      S->>MP: postMessage(buffered dataEvent for "TestEvent")
      MP->>C: onmessage(buffered dataEvent for "TestEvent")
    else
      Note over S: No buffered events to flush
    end

    %% Now, the Server publishes a new event "TestEvent"
    S->>S: publish("TestEvent", data)
    alt Subscriber exists
      S->>MP: postMessage({type:"dataEvent", name:"TestEvent", data})
      MP->>C: onmessage({type:"dataEvent", name:"TestEvent", data})
      Note over C: Client processes the dataEvent
    else
      S->>S: Buffer event "TestEvent" with timeout
      Note over S: Event buffered until a subscriber appears
    end

```

* * *

## 发展

```bash
# Install dependencies
npm install

# Run tests (requires Deno)
npm test

# Build project
npm run build
```

* * *

_麻省理工学院执照 2024年 [阿利坎·伯德崎](https://alykam.com/)_ _[报告问题](https://github.com/collidor/event/issues)_

## 常见问题

### @collidor/event 是什么？

一个小型的图书馆,用于创建,注册和收听事件\.

### 如何安装 @collidor/event？

在项目目录运行 npm install @collidor/event，或使用 pnpm add / yarn add / bun add。

### @collidor/event 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @collidor/event 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @collidor/event 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @collidor/event 可以商用吗？

@collidor/event 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @collidor/event 的下载量有多少？

根据 npm 官方下载统计，@collidor/event 在 2026/10/11 – 2026/11/09 这 30 天内被下载 7,900 次，日均约 263 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @collidor/event 还在维护吗？

最新版本 4\.7\.2 发布于 2026/10/09（1 个月前）；至今共发布 56 个版本，其中过去 12 个月发布了 9 个；首次发布于 2025/02/10。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

