Gntem
Gntem

Reputation: 7155

Events or functions on javascript class

I'm using EventEmitter in some classes, but i'm really confused whether event listening and events emitting are more efficient than calling object methods?

I want the object to be able to listen for a number of events that are emitted to it, and also emit a number of events to the object that originally emitted the events to the object and some others objects as well.

And i pretty much confused whether when should i use functions which in turn call other object methods and so on.

Upvotes: 1

Views: 155

Answers (1)

Sebastian vom Meer
Sebastian vom Meer

Reputation: 5241

Events improve module decoupling. It is all about this simple question: "How many files do I have to touch to modify or add feature X?"

A simple example: You have a web server, a logging module and a starting script, which ties both together on startup. The function call way looks like this:

// Startup.js
var Startup = function() {
    var logger = new Logger();
    var server = new Server(logger);
};

// Logger.js
var Logger = function() {
};
Logger.prototype.log = function(msg) {
    console.log(msg);
};

// Server.js
var Server = function(logger) {
    this.logger = logger;
};
Server.prototype.start() {
    this.logger.log("Start server...");
};

You can see that Startup knows all classes and Server knows about logger and how to use it. If I want to rename Logger's function log to write I have to touch Logger and Server.

Now let's have a look at a event driven approach:

// Startup.js
var Startup = function() {
    var logger = new Logger();
    var server = new Server();
    server.addListener(logger);
};

// Logger.js
var Logger = function() {
    this.on("startup", function(msg) {
        console.log(msg);
    });
};
Logger.prototype.__proto__ = EventEmitter.prototype;

// Server.js
var Server = function() {
};
Server.prototype.start() {
    this.emit("startup", "Start server...");
};
Server.prototype.__proto__ = EventEmitter.prototype;

Now Logger and Server don't know each other. I can rename log and all I have to touch is Logger.js. I can even remove Logger or add more Loggers, all of them working with Server. But I never have to touch Server.js.

This is a simple example and decoupling doen't look important here. But the larger a project gets, the more benefits come up.

You can Unit-Test Server without having to mock Logger. And Logger is only one dependency. Imagine the advantage if Server had five or more submodules you have to simulate.

I hope this helps you to understand the benefits of event driven architectures.

Upvotes: 2

Related Questions