> For the complete documentation index, see [llms.txt](https://ddzy.gitbook.io/ts-utility-plugins-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ddzy.gitbook.io/ts-utility-plugins-docs/utility/untitled/event-emitter.md).

# event-emitter

### 说明

模拟实现 `EventEmitter`

### 源码

<https://github.com/ddzy/ts-utility-plugins/tree/master/src/ddzy/utility/algorithm/event-emitter>

### 用法

{% code title="eventEmitter.test.ts" %}

```typescript
import { EventEmitter } from "../../utility/algorithm/event-emitter";

// ? EventEmitter
describe('EventEmitter tests', () => {
  test("EventEmitter.handleOn should put handlers into events and return the handler's own index", () => {
    const event = new EventEmitter({});
    const fun1 = function () {
      console.log('fun1');
    }
    const fun2 = function () {
      console.log('fun2');
    }
    const received = [
      {
        type: 'click',
        handler: fun1,
      },
      {
        type: 'click',
        handler: fun2,
      }
    ];
    const expected = [
      {
        type: 'click',
        index: 0,
      },
      {
        type: 'click',
        index: 1,
      }
    ];

    received.forEach(function (v, i) {
      const result = event.handleOn(v.type, v.handler);
      expect(result).toEqual(expected[i]);
    });
  });

  test('EventEmitter.handleRemove should remove the `dest handler` from events', () => {
    const event = new EventEmitter({});
    const fun1 = function () {
      console.log('fun1');
    }
    const fun2 = function () {
      console.log('fun2');
    }

    const r1 = event.handleOn('click', fun1);
    const r2 = event.handleOn('click', fun2);

    event.handleRemove(r2);

    let result: boolean = false;
    const events = event.events;
    events['click'].forEach(function (v, i) {
      if (i === r2.index) {
        if (!v) {
          result = true;
        }
      }
    });

    expect(result).toBeTruthy();
  });
});
```

{% endcode %}

### API

| Name         | Type                                                                                          | Description             |
| ------------ | --------------------------------------------------------------------------------------------- | ----------------------- |
| handleOn     | <p>(type: string, handler: EventHandler) => {</p><p>  type: string, index: number</p><p>}</p> | 放置事件                    |
| handleEmit   | (type: string) => EventEmitter                                                                | 发射事件                    |
| handleRemove | (options: { type: string, index: number, },) => EventEmitter                                  | 移除某 `type` 的某个`handler` |
