Emitters vs import function on modular JS - Which to choose

Viewed 112

We can communicate between modules by:

  1. Using an Event Emitter
  2. Importing the function from an external module

Is there any best practice when it comes to choosing between the two?

I understand we can only import the function if we need a to use a returned value. But, when we don't, how do we decide if we import the function or we use an event emitter to trigger the same function?

(In case it matters, I'm talking about front-end JS modules to combine with something like Rollupjs)

Import example

//app.js
import { say } from 'actions.js';

function demo(){
  .... 
  say('Hello');
}
//say.js
export function say(content){
   console.log(content);
}

Event Emitter example

//app.js
import { eventEmitter } from 'eventEmitter.js';
import 'say.js';

function demo(){
  .... 
  eventEmitter.emit('say', 'hello');
}
//say.js
import { eventEmitter } from 'eventEmitter.js';

eventEmitter.on('say', say);

function say(content){
   console.log(content);
}

The advantage I see when using Event Emitters is that we can prevent circular dependencies during the build. But I would love to see what other people think about this.

1 Answers

Two things that you mention have different purposes.
Imports are used for code separation and better project structure while event emitters are used like an event bus.
Some things to consider are:

  • when using (or overusing) event bus you code quickly becomes hard to maintain and your code turns into a bunch of if/else statements (in your particular example the logic can end up being duplicated in multiple callbacks);
  • when using imports you have 1 place where the code lives and as per ESModules spec, browsers should make sure that the code gets imported (downloaded over the network) only once no matter how many times you use the import {something} from 'somewhere' on a single page.

I understand we can only import the function if we need a to use a returned value.

This is simply not true, you can import functions that do not return anything. For example, they modify the object you pass into that function or that code is some kind of a special logger.

Related