Why use Node js EventEmitter instead of just a plain function

0 votes

The creation of node EventEmitters is covered in every article on them that I have read. But I haven't come across a specific instance of why using them would be preferable to using a straightforward function. This is an example of how to utilise the EventEmitter class on a custom object via its function Object() { [native code] } from a book I'm currently reading.

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

When working with nodes, do event emitters come as a design choice or are they required? I'm aware that it's important to understand them because many modules use this design pattern, but I'm keen to know if choosing factories over constructors, for example, is a similar decision. Is there anything I can do with EventEmitters that I can't do with functions, to put it another way?

Sep 6, 2022 in Node-js by Vaani
• 7,070 points

edited 4 days ago 13 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP