# @benzinga/subscribable 中文文档

规范地址：https://npmcn.com/package/%40benzinga/subscribable/

版本：2\.0\.10
npm 元数据更新时间：2025-04-28T17:56:50.312Z
中文译文更新时间：2026-11-07T22:48:53.384Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40benzinga/subscribable
原文对照：https://npmcn.com/package/%40benzinga/subscribable/?lang=original
项目主页：https://github.com/Benzinga/js-tools

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

- 包体积（解压后）：24 kB，8 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2023-02-10T00:37:17.484Z
- 最新版本发布：2025-04-14T17:27:15.438Z
- 近 30 天下载量：2876（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：12（近 12 个月 0 个）

## 中文简介

这个项目之所以可能,是因为

## 安装

```sh
npm install @benzinga/subscribable
```

也可以使用：`pnpm add @benzinga/subscribable`、`yarn add @benzinga/subscribable`、`bun add @benzinga/subscribable`

## README

# 可分解

这个项目之所以可能,是因为

[![Benzinga Logo](https://import.cdn.thinkific.com/222214/D3r5EJy9SZaNsaY7dQsj_Benzinga-logo-navy.svg)](https://npmcn.com/package/%40benzinga/subscribable/www.benzinga.com)

[![ZSoft Logo](https://raw.githubusercontent.com/ZNackasha/CDN/refs/heads/main/zsoft-no-size.svg)](https://github.com/znackasha)

Subscriptable软件包是一个简单的页面,可以让您能够使类子被允许向订阅者发送事件. 这仅仅是通过继承可分层分类来完成的.

## 制作基本分册

```ts
import {
  Subscribable,
 Subscription,
 SubscribableEvent,
} from '@benzinga/subscribable';


interface SetAddEvents extends SubscribableEvent<'add'> { // one of the events that can be dispatched
 item: number;
}

interface SetRemoveEvents { // second event that can be dispatched as you can see you don't have to implement SubscribableEvent directly all SubscribableEvent is doing is simply adding type key with the value given
 type: 'remove';
 item: number;
}

type SetEvents = SetAddEvents | SetRemoveEvents; // all the events that can be fired by the subscribable

class SetSubscribable extends Subscribable<SetEvents> { // extending the subscribable and telling the subscribable when events can be fired
 private items = new Set<number>();

 public add = (num: number ): void => {
  this.items.add(num);
  this.dispatch({type: 'add', item: num}); // fire out the event inherited from  Subscribable
 }

 public remove = (num: number ): void => {
  this.items.delete(num);
  this.dispatch({type: 'remove', item: num}); // fire out the event inherited from  Subscribable
 }
}

type SetSubscription = ReturnType<SetSubscribable['subscribe']>; // this is a helper type that represents value returned from the
```

## 使用基本分册

```ts
import SetSubscribable from './set';

const set = new SetSubscribable(); // create a new instance
const setSubscribe1 = set.subscribe(event => { // subscribe to events
 switch (event.type) {
  case 'add':
   console.log(`added ${event.item}`);
   break;
  case 'remove':
   console.log(`removed ${event.item}`);
   break;
 }
})

const setSubscribe2: SetSubscription = set.subscribe(event => { // subscribe to events
 switch (event.type) {
  case 'add':
   console.log(`included ${event.item}`);
   break;
  case 'remove':
   console.log(`erased ${event.item}`);
   break;
 }
})

console.log('start');
set.add(1);
set.remove(1);
setSubscribe1.unsubscribe(); // unsubscribe the first subscription
console.log('unsubscribe');
set.add(2);
set.remove(2);
setSubscribe2.update(event => console.log('update')); // update the callback of the subscription
set.add(3);
set.remove(3);
setSubscribe2.unsubscribe(); // unsubscribe the second subscription
console.log('end');
```

这将产生以下产出

```log
[LOG]: "start"
[LOG]: "added 1"
[LOG]: "included 1"
[LOG]: "removed 1"
[LOG]: "erased 1"
[LOG]: "unsubscribe"
[LOG]: "included 2"
[LOG]: "erased 2"
[LOG]: "update"
[LOG]: "update"
[LOG]: "end"
```

# 类订阅

这个 `Subscription` 类以通义为输入.

-   `Events`: 仅如上所示

```ts
class SetSubscribable extends Subscription<SetEvents>
```

## 发送

```ts
protected dispatch(event : Events) => void
```

-   这个功能是受保护的,可以让班级开火/发送出新的事件.

## 订阅

```ts
public subscribe(callback: (event: Events) => void, ..._args: readonly unknown[]) => Subscription<Events>
```

-   这是公众的功能, 它会回来 `Subscription` 用于两者 `unsubscribe` 财务报告和审定财务报表 `update` 召回电话.

## 第一次订阅

```ts
protected onFirstSubscription = () => void;
```

-   继承等级 `Subscribable` 也可以执行 `onFirstSubscription`。如果您想要在初始化某物之前等待订阅者,则此功能是有用的.

## 零订阅

```ts
protected onZeroSubscriptions = () => void;
```

-   继承等级 `Subscribable` 也可以执行 `onZeroSubscriptions`。如果在没有订阅者的情况下想要进行一些清理,则此功能是有用的.

## 订阅

```ts
protected onSubscribe = (..._args: readonly unknown[]): void;
```

-   页:1 `onSubscribe` 允许您在添加新的订阅者时运行您想要的任意类型的逻辑.

## 取消订阅

```ts
protected onUnsubscribe = () => void;
```

-   继承等级 `Subscribable` 也可以执行 `onUnsubscribe`。如果想要跟踪订阅者的数量,此选项将有所帮助。 您可以使用 `constructor` 调用和减少这里.

# 扩展订阅类

这个 `ExtendedSubscription` 继承从 `Subscription` 课取出两个同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同名同.

-   `Events`: 仅如上所示
-   `Extension`: 表示将延长订阅时间。 比如说

```ts
interface SetExtends {
 add: (num: number ) => void
 remove: (num: number ) => void
}

class SetSubscribable extends ExtendedSubscription<SetEvents, SetExtends>
```

这将显示返回的订阅将拥有 `add` 财务报告和审定财务报表 `remove` 可调用函数。 完成这个任务 您需要返回 `SetExtends` 输入 `onSubscription` 以后再谈这个.

## 类 `Subscription` 对 `ExtendedSubscription`

`ExtendedSubscription` 仅仅是 `Subscription` ,其中的订阅函数已被超载以添加返回的数据 `onSubscription` 将添加到订阅的返回中.

## 订阅

```ts
public subscribe(callback: (event: Events) => void, ..._args: readonly unknown[]) => Subscription<Events, Extension>
```

-   这是公众的功能, 它会回来 `Subscription` 用于两者 `unsubscribe` 财务报告和审定财务报表 `update` 召回电话。 还将包括: `Extended` 函数返回.

## 订阅

```ts
protected onSubscribe = (..._args: readonly unknown[]): Extension
```

-   页:1 `onSubscribe` 允许您在添加新订阅器但类型返回时运行您想要的任意类型的逻辑 `Extension` 需要时间.

```ts
interface SetExtends {
 add: (num: number ) => void
 remove: (num: number ) => void
}

class SetSubscribable extends ExtendedSubscription<SetEvents, SetExtends> {
 onSubscribe = () => ({ // remember that () => ({}) is shorthand for () => { return {}}
  open: this.open,
  remove: this.remove,
 })
}
```

这将允许您拨打 `add` 财务报告和审定财务报表 `remove` 编辑 `Subscription` 打电话后返回 `subscribe`

如果您只希望订阅者设置为 `add` 财务报告和审定财务报表 `remove` 可以简单制作的项目 `private` 在课堂上。 评估这些功能的唯一方法是通过 `Subscription`。 。 。 .

## 进行基本的扩展订阅

```ts
import {
  Subscribable,
 Subscription,
 SubscribableEvent,
} from '@benzinga/subscribable';


interface SetAddEvents extends SubscribableEvent<'add'> { // one of the events that can be dispatched
 item: number;
}

interface SetRemoveEvents { // second event that can be dispatched as you can see you don't have to implement SubscribableEvent directly all SubscribableEvent is doing is simply adding type key with the value given
 type: 'remove';
 item: number;
}

type SetEvents = SetAddEvents | SetRemoveEvents; // all the events that can be fired by the subscribable

interface SetSubscribableFunctions {
 add: (num: number) => void;
 remove: (num: number) => void
}

class SetSubscribable extends ExtendedSubscribable<SetEvents, SetSubscribableFunctions> { // extending the subscribable and telling the subscribable when events can be fired
 private items = new Set<number>();

 private add = (num: number ): void => { // note i made add protected to make sure that only subscribers can add
  this.items.add(num);
  this.dispatch({type: 'add', item: num}); // fire out the event inherited from  Subscribable
 }

 private remove = (num: number ): void => { // note i made add protected to make sure that only subscribers can remove
  this.items.delete(num);
  this.dispatch({type: 'remove', item: num}); // fire out the event inherited from  Subscribable
 }

 protected onSubscribe = () => ({
  add: this.add,
  remove: this.remove,
 })
}

type SetSubscription = ReturnType<SetSubscribable['subscribe']>; // this is a helper type that represents value returned from the
```

## 使用基本分册

```ts
import SetSubscribable from './set';

const set = new SetSubscribable(); // create a new instance
const setSubscribe1 = set.subscribe(event => { // subscribe to events
 switch (event.type) {
  case 'add':
   console.log(`added ${event.item}`);
   break;
  case 'remove':
   console.log(`removed ${event.item}`);
   break;
 }
})

const setSubscribe2: SetSubscription = set.subscribe(event => { // subscribe to events
 switch (event.type) {
  case 'add':
   console.log(`included ${event.item}`);
   break;
  case 'remove':
   console.log(`erased ${event.item}`);
   break;
 }
})

console.log('start');
setSubscribe1.add(1);
setSubscribe1.remove(1);
setSubscribe1.unsubscribe(); // unsubscribe the first subscription
console.log('unsubscribe');
setSubscribe1.add(2);
setSubscribe1.remove(2);
setSubscribe2.update(event => console.log('update')); // update the callback of the subscription
setSubscribe2.add(3);
setSubscribe2.remove(3);
setSubscribe2.unsubscribe(); // unsubscribe the second subscription
console.log('end');
```

# 可拆卸

这个库是用 [无](https://nx.dev/)。 。 。 .

## 运行单元测试

运行 `nx test utils-subscribable` 通过 [欢乐](https://jestjs.io/)。 。 。 .

## 常见问题

### @benzinga/subscribable 是什么？

这个项目之所以可能,是因为

### 如何安装 @benzinga/subscribable？

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

### @benzinga/subscribable 支持 TypeScript 吗？

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

### @benzinga/subscribable 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @benzinga/subscribable 可以商用吗？

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

### @benzinga/subscribable 的下载量有多少？

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

### @benzinga/subscribable 还在维护吗？

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

