1
0

More than 1 year has passed since last update.

【TypeScript】EventEmitterを継承してクラスを作る

Last updated at Posted at 2022-05-22

typescriptにおいてEventEmitterを継承したクラスを作成します。

EventEmitterとは?

Node.jsの標準モジュールの一つ、Eventsから読み込めるクラス。イベントリスナー(イベント実行時に動く関数)の登録を行い、イベントの実行をトリガーとして登録した処理を実行することができる。

EventEmitterを使ってみよう

EventEmitterをimportし、インスタンスを作成します。

import { EventEmitter } from "events";
const emitter = new EventEmitter();

イベントリスナーの登録処理はeventEmitter.onもしくはeventEmitter.addListenerで行います。ちなみにこの二つは同じものだそうです

emitter.on('test', () =>{
    console.log('hello, world!');
})

これで実行。'hello, world!'の出力が得られます。

emitter.emit('test');

イベントリスナーに引数を持たせるときはこのように書きます。

emitter.on('testArgument', (name: string) =>{
    console.log(name + ', hello, world!');
})


emitter.emit('testArgument', "takashi");

また、一度しか実行されないリスナーの登録eventEmitter.onceやイベントリスナーの削除を行うeventEmitter.removeListener(もしくはeventEmitter.off)等が用意されています。

emitter.once('testObj', (obj:any) =>{
    console.log(obj.name + ', hello, world!');
})
emitter.emit('testObj', {name: "hiroshi"});
emitter.emit('testObj', {name: "hiroshi"}); // こちらは実行されない
const testFunc = () => {
    console.log("testFunc");
}
emitter.on("testFunc", testFunc);
emitter.emit('testFunc'); // 実行される
emitter.removeListener("testFunc", testFunc);
emitter.emit('testFunc'); // 実行されない

EventEmitterクラスの継承

EventEmitterを継承してイベントを登録できるクラスを作成してみましょう。

import { EventEmitter } from "events";


export class TestEmit extends EventEmitter{
    constructor(){
        super();
        this.on("test", (name: string)=>{
            console.log(name + ": hello, world!");
        });
    }
}

このファイルを外部ファイルから読み込み、testイベントを動かしてみます。また、同時に外部ファイルからnewEventイベントを新しく登録し、動かしてみます。

import {TestEmit} from "./testClass";

const testEmit = new TestEmit();

testEmit.emit("test", "hiro");
// hiro: hello, world!


testEmit.on("newEvent", ()=>{
    console.log("newEvent");
});
testEmit.emit("newEvent");
// newEvent

これで外部から読み込み、イベントを操作することができました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0