samedi 3 septembre 2016

Why use Node.js EventEmitter instead of just a plain function?

Every article I read about node EventEmitters talks about how to create them. However, I have not seen a concrete example of why to use them instead of just a simple function. So for example , this is an example in a book I am reading of how to use the EventEmitter class on custom object via its constructor.


    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);


However, the following gives me the same result:


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);


I'm wondering if event emitters are a design choice or a necessity when working with node. I know its a necessity to understand them since many modules employ this pattern, but I am curious if that choice is analogous to using factories over constructors etc. In other words is there anything I can do with EventEmitters that I can't do with functions ?

Aucun commentaire:

Enregistrer un commentaire