We can communicate between modules by:
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)
//app.js
import { say } from 'actions.js';
function demo(){
....
say('Hello');
}
//say.js
export function say(content){
console.log(content);
}
//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.
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:
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.