Wednesday, 12 January 2022

Emitters vs import function on modular JS - Which to choose

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.



from Emitters vs import function on modular JS - Which to choose

No comments:

Post a Comment