Utilize external modules in factory by employing Object.assign for encapsulation

In my factory function, I have the following setup:

import moduleA from'./modulea'
import moduleB from'./moduleb'
import { componentA, componentB } from './components'

module.exports = () => {
    //DECLARE VARIABLES SHARED BY FUNCTIONS
    const util = moduleA.util() //RETURNS OBJECT

    return Object.assign({}, {
        componentA,
        componentB
    }
}

Initially, componentA and componentB were functions within the factory function, allowing access to any imports or variables. However, since moving them to separate files in './components', I am facing issues with importing modules or declared variables into the components.

import moduleA from'./modulea'
import moduleB from'./moduleb'

module.exports = () => {
    //DECLARE VARIABLES SHARED BY FUNCTIONS
    const util = moduleA.util() //RETURNS OBJECT

    const componentA = () => {
        //MODULES AVAILABLE
        //DECLARED VARIABLES AVAILABLE
        //DO STUFF
    }

    const componentA = () => {
        //MODULES AVAILABLE
        //DECLARED VARIABLES AVAILABLE
        //DO STUFF
    }

    return Object.assign({}, {
        componentA,
        componentB
    }
}

The imported modules and declared variables are no longer accessible to the separate components despite using Object.assign. I have even attempted passing them into Object.assign without success.

Is there a way to make the imported modules and declared variables available to the imported components, so that I can divide the factory function into smaller components located in separate files, while maintaining accessibility without individual imports in each component file? My goal is to achieve this using closure.

Answer №1

When creating your components module, make sure to import any necessary modules.

// Import required modules for the "components" module
import moduleA from'./modulea'
import moduleB from'./moduleb'

const util = moduleA.util()

export const componentA = () => {
    //MODULES AVAILABLE
    //DECLARED VARIABLES AVAILABLE
    //DO STUFF
}

export const componentA = () => {
    //MODULES AVAILABLE
    //DECLARED VARIABLES AVAILABLE
    //DO STUFF
}

UPDATE (based on comment):

While these suggestions may not be ideal, here are a couple of alternative approaches:

1) Utilize "this" to attach everything:

// Attach functions to "this" in the "components" module
export function componentA() {
    this.moduleA
    this.moduleB
    this.util
}

export function componentA() {
    this.moduleA
    this.moduleB
    this.util
}

In your main module:

module.exports = () => {
    //DECLARE SHARED VARIABLES
    const util = moduleA.util() //RETURNS OBJECT

    return Object.assign({}, {
        componentA,
        componentB,

        // other properties expected by the component functions
        moduleA,
        moduleB,
        util
    }
}

Or 2) Pass all dependencies as arguments:

// Receive dependencies as arguments in the "components" module
export const componentA = (moduleA, moduleB, util) => {
    //MODULES AVAILABLE
    //DECLARED VARIABLES AVAILABLE
    //DO STUFF
}

export const componentA = (moduleA, moduleB, util) => {
    //MODULES AVAILABLE
    //DECLARED VARIABLES AVAILABLE
    //DO STUFF
}

In your main module:

module.exports = () => {
    //DECLARE SHARED VARIABLES
    const util = moduleA.util() //RETURNS OBJECT

    return Object.assign({}, {
        componentA: (...args) => componentA(moduleA, moduleB, util, ...args),
        componentB: (...args) => componentB(moduleA, moduleB, util, ...args),
    }
}

As a side note:

each function in components has it's own file ... the functions that are now methods on that new object

If you're defining methods in separate files, you might want to reevaluate your design as it could indicate a deeper issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the Webpack library and libraryTarget settings to establish our own custom library as a global variable

I currently have a library named "xyz" that is being imported as a node module from the npm registry. Now, I want to incorporate it as a library and make it accessible under the global name "abc". To achieve this, I plan to utilize webpack configuration. ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

Develop your own personalized Angular schematics that produces a file that begins with an underscore

Having trouble with custom Angular schematics file naming. I'm trying to create a theme SCSS file that starts with an underscore followed by a double underscore as a delimiter. For instance, I want the file name to be _mouse-theme.scss, using the nam ...

Positioning the comments box on Facebook platform allows users to

Need assistance, I recently integrated the Facebook comments box into my Arabic website, but I am facing an issue where the position of the box keeps moving to the left. Here is an example of my website: Could someone please suggest a solution to fix the ...

constructing a nested container using XMLHttpRequest

I am working on creating a nested div-container structure using AJAX and adding the text "Hello World" to the inner container. The outer container serves as a holder for the inner container in this case. Below is the code I have written: index.html: ...

Asynchronous operations and recursive functions in the world of Node.js

When working with express and mongoose, I frequently find myself needing to perform batch operations on collections. However, the typical approach involves callbacks in nodejs concurrency coding, which can be cumbersome. // given a collection C var i = 0 ...

The commencement of setTimeout relies on my decision to halt the page's operation

During a form submission, my jQuery AJAX function is used to query the amount of data uploaded from a file. This information is then utilized in creating a progress bar. Here is an example of my JavaScript file: var formSubmitted = ''; var count ...

Obtain date and currency formatting preferences

How can I retrieve the user's preferences for date and currency formats using JavaScript? ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

What is the NEDB node.js equivalent of selecting all columns with SELECT *?

As a newcomer to nedb with node.js, I'm curious about how to showcase all records or SELECT * FROM tablename. I understand that nedb operates differently from mysql, but I need to integrate a database within my electron application. I want to determin ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

Installing material-ui using npm does not always result in getting the most up-to-date version

I'm currently facing a dilemma with an abandoned project that serves as the admin tool for my current project. The Material-UI version used in this project is 0.19.4. However, when I remove the dependency from my package.json file and execute npm inst ...

Adding JSON data to an array with a click - a step-by-step guide

As I dive into working with React and integrating API JSON data into my project, I've encountered a small hurdle. I've implemented a function that allows users to enter a search query, resulting in a list of devices associated with their input be ...

Strength Indicator for Passwords - Utilizing Html & Javascript/Ajax

Anyone know of a Password Strength Visualizer tool that provides a visual representation similar to Gmail's when creating a new account? I'm interested in displaying the password strength visually for users. If you have any source code you' ...

How can I incorporate a spinning cog from Font Awesome into a jQuery click event?

I am looking to incorporate a spinning font awesome cog while the data is being fetched and remove it once the process is complete. Here is the HTML snippet that needs to be inserted: <i class="fa fa-spin fa-cog"></i> And this is the accompa ...

ReserveYourSpot: Effortless Seat Reservation with AngularJS at the Click of a Button [GIF]

ReserveYourSpot: An innovative AngularJS application designed to streamline the process of reserving seats for a movie show, similar to popular platforms like BookMyShow. https://i.stack.imgur.com/PZk1I.gif Interactive User Functions (Use Cases): A ...

How to deselect a checkbox using AngularJS

I have a checklist of items <input type="checkbox" ng-model="servicesModel" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)"/> and I need to unselect the currently selected checkbox $scope.toggleSelection = function toggl ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

Tips for concealing information that is scrolled beneath a translucent layer

In the scenario where you have two overlapping divs, with the top one being transparent, the goal is to have the bottom div hide as it goes under the top transparent div when scrolling. It's important that the bottom div's visibility is not compl ...