我读到的关于Node.js事件发射器的文章都是关于如何创建它们。然而,我还没有看到一个具体的例子,说明为什么要使用它们而不仅仅使用简单的函数。例如,这是我在一本书中阅读的如何通过构造函数在自定义对象上使用EventEmitter类的示例。
var util = require('util');
var events = require('events');
var AudioDevice = {
play: function(track) {
// Stub: Trigger playback through iTunes, mpg123, etc.
console.log("playing song: " + track);
},
stop: function() {
console.log("song stopped");
}
};
function MusicPlayer() {
this.playing = false;
events.EventEmitter.call(this);
}
util.inherits(MusicPlayer, events.EventEmitter);
var musicPlayer = new MusicPlayer();
musicPlayer.on('play', function(track) {
this.playing = true;
AudioDevice.play(track);
});
musicPlayer.on('stop', function() {
this.playing = false;
AudioDevice.stop();
});
musicPlayer.emit('play', 'The Roots - The Fire');
setTimeout(function() {
musicPlayer.emit('stop');
}, 1000);
然而,以下代码也可以得到相同的结果:
var AudioDevice = {
play: function(track) {
// Stub: Trigger playback through iTunes, mpg123, etc.
console.log("playing song: " + track);
},
stop: function() {
console.log("song stopped");
}
};
function createMusicPlayer() {
var musicPlayer = {};
musicPlayer.playing = false;
musicPlayer.play = function(track) {
musicPlayer.playing = true;
AudioDevice.play(track);
},
musicPlayer.stop = function(track) {
musicPlayer.playing = false;
AudioDevice.stop();
}
return musicPlayer
}
var musicPlayer = createMusicPlayer();
musicPlayer.play('The Roots - The Fire');
setTimeout(function() {
musicPlayer.stop();
}, 1000);
我想知道在 Node.js 中使用事件发射器是一种设计选择还是必需品。我知道理解它们是必要的,因为许多模块采用了这种模式,但我很好奇是否选择它类似于使用工厂函数而不是构造函数等。换句话说,我能否通过 EventEmitters 做到一些无法使用函数实现的事情?