7
9

More than 5 years have passed since last update.

Node.js EventEmitterの基本

Posted at

emitter.on : リスナーの追加
emitter.once : 一回限りのリスナーの追加
emitter.removeListener : リスナーの削除

emitter.emit(event, [arg1], [arg2], [...]) : eventに対応するリスナーを実行argは引数

以下のコードで動作確認。

var util = require("util");
var events = require('events');

function MySample() {
    events.EventEmitter.call(this);
}
util.inherits(MySample, events.EventEmitter);

MySample.prototype.log = function(data) {
    console.log(data);
}

var sample = new MySample();

1.onとonceの違い

sample.on('data', sample.log);
sample.once('data_once', sample.log);


sample.emit('data', 1);
sample.emit('data', 2);
sample.emit('data_once', 3);
sample.emit('data_once', 4);

実行結果

1
2
3

onceは引数3のemitでリスナーから削除されている。

2.onceをonとremoveListenerで表現

sample.on('data', sample.log);
sample.on('data_once', sample.log);

sample.emit('data', 1);
sample.emit('data', 2);
sample.emit('data_once', 3);
// 3を実行後に'data_once'リスナーを削除する
sample.removeListener("data_once", sample.log);

sample.emit('data_once', 4);

実行結果

1
2
3

console.log(sample.listeners('data_once'));を適所に入れてやるとリスナーの状態がわかる。
once指定のときとonでは中身のfunctionが異なるが1と2は実質同じ動きをする。

7
9
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
7
9