0

I have an object instance that's used by several different modules in my code. The instance itself gets edited during different events, then the modules use it to redraw the page.

For example:

// index.js
import populateProjects from 'populateProjects.js'
import populateItems from 'populateItems.js'

let projects = new projectList() // Projects in index.js's scope

projects.addProject('Project 1')
projects.getProject(0).addItem('Item 1')

// Note how I need to pass the 'projects' into the modules below
populateProjects(projects)
populateItems(projects)

//I would prefer both modules to have access to the same instance of 'projects' so that I don't need to pass it into them:
populateProjects() //'projects' is imported in the modules
populateItems()    //regardless of where they're called

Right now, I keep passing it into the module functions when they're called, but that means that I need to always have it in the scope of the script that's calling the module. I can get around this by using global variables but I'd rather not pollute the namespace for other modules that don't rely on it.

Is there a way that I can make this instance accessible in the specific modules that need it and still have it editable? Maybe using import?

Brother58697
  • 2,290
  • 2
  • 4
  • 12
  • 2
    Could you accompany your question with some code to better understand the problem? – Swiffy Jun 09 '22 at 12:59
  • I found the answer, but I'll some code and the answer to make it a proper reference for others – Brother58697 Jun 09 '22 at 13:10
  • If you found the answer in StackOverflow, link it here and I'll flag this as a duplicate. Otherwise, great idea! – Swiffy Jun 09 '22 at 13:13
  • [This]( https://stackoverflow.com/a/57050195/17804016) is the answer. Which is that imported modules in ES6 are singletons. So if I export the instance from its own module, if I import it into any other modules, it's the same instance. I can write a solution given the example I put in my question. Let me know – Brother58697 Jun 09 '22 at 13:24
  • Yeah, It's the same one I linked in my comment. Not sure why my hyperlink didn't hyperlink though. I can write an example answer according to my code above. – Brother58697 Jun 09 '22 at 13:30
  • 1
    It's all good, that comment happens automatically when a question gets flagged as duplicate. :) – Swiffy Jun 09 '22 at 13:32

0 Answers0