Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!