The Controller of Conversations

In the HTML code, there is a dialog element with an identification of divMyDialog1. This dialog is connected to a JavaScript class called MyDialog1. Each dialog has its own unique id and associated class name.

 MyDialog1 = function(divStr){
    this.divStr = divStr;
    ...
 }

There are multiple dialogs with their respective classes in the project. The goal is to link each dialog's id with its corresponding class. Some classes may have multiple instances with different div ids.

The question arises: How can this be achieved efficiently?

An approach could look like this:

 let dialogARR = [];
 [{divStr: "divMyDialog1", className: MyDialog1},
 {divStr: "divSomethingElse", className: DialogWibble},
 {divStr: "divPingPong", className: DialogWobble}].forEach(obj => dialogARR.push(new obj.className(obj.divStr)));

Answer №1

Iterate over the array, extracting the attributes from each element and then instantiating the class constructor function using new.

dialogArr.forEach(({createElementString, classType}) => new classType(createElementString));

If you require the instances, you can utilize .map() in place of .forEach(), which will output an array containing the instances.

Answer №2

One possible solution could be:

class PopUpBox(){
   Constructor(name, content){
       this.name = name;
       this.content = content;
   }
}

Then you can create instances of the PopUpBox class and add them to an array like this:

let popUpBoxes = [];

 [new PopUpBox("box1", "Content for box 1"), new PopUpBox("box2", "Content for box 2")].forEach(box => popUpBoxes.push(box));

This is just one approach you could take, feel free to suggest any improvements.

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

What is the best way to incorporate a formArray into a formGroup?

Before anything else, I want to apologize for any errors in my English. I seem to be having trouble adding an array field to a formGroup. My issue arises when attempting to use the push method to add a formArray to my rate formGroup. It appears that the ...

PHP: Bootstrap CSS for Carousels

I'm experiencing some difficulties with the Bootstrap CSS Carousel on my website. The left and right arrows seem to be unresponsive, and the slides are not transitioning automatically. I have been unable to identify the root cause of this issue. Belo ...

Inheritance of nested directives in Angular.js

Click here for a live example I'm trying to understand how 00B can be contained within 00A. Here is the code snippet: <div directive-one="['foo', 'bar']"> <directive-two /> </div> In this code, the directi ...

Report the error efficiently without terminating the process

I created a tool for users to submit data. If the submitted data does not pass validation (validation returns false), I need to respond with an error 500 status code to the user. The issue is that when I use res.status(500), it causes the program to exit ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

What is the most efficient way to retrieve the key at a specific index within a JavaScript map object?

If I have the map object shown below: const items = new Map([['item1','A'], ['item2','B'], ['item3', 'C']]) I am trying to retrieve the key at index 2. Is there a method other than using a for ...

The drawbacks of using toJS() in React Redux: Is it really necessary in mapStateToProps()?

After reading through the Redux documentation, I came across a recommendation to not use Immutable with Redux. This advice has left me feeling confused. Why should I avoid using toJS() in the mapStateToProps function? It seems that React already uses Dee ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

Determine the quantity of items currently in an active state

I created a function that toggles the active state of list items when clicked: React toggleActive: function(item){ item.active = !item.active; }, JSX <li key={property.id} onClick={() => this.toggleActive(property)}> Is there a way to count ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

The absence of shapes in containers is noticeable in the stage setting

After spending some time troubleshooting the issue, I have encountered a problem with my code on JSFiddle Code. My goal was to place one large container on the stage that contains two smaller containers, each holding a shape. However, despite no errors bei ...

"The issue seems to stem from a snippet of compact JavaScript

I am facing an issue with a list item that contains both an image and text. The text is overlapping the image, but when I hover over the text, it disappears and only the picture is visible. Here is the HTML code snippet: <ul> <li><img ...

AngularJs is not responsive to sending POST requests with hidden <input> values

Within my web application, there are multiple forms on a single page. I am looking to utilize AngularJS to submit a specific form. Each form requires a unique ID with a hidden value for submission. However, using value="UNIQUE_ID" in a hidden input field ...

What changes should I make to my save function in order to handle both saving and editing user information seamlessly?

My goal for the save function is to achieve two tasks: 1. Save user in table - Completed 2. Update user in table - In progress Save function snippet: var buildUser = function () { $('#save').click(function () { var newUser = {}; ...

Struggling to handle JSON response in JavaScript

Upon receiving a JSON response from the Amazon API, here is how it appears: { "Result": { "Data": { "Title": "HALO 3 (XBOX 360 - REGION FREE)", "FormattedPrice": "$19.95", "Source": "Product Description", "Content": "The epi ...

A one-page digital space that functions as a dynamic slide show

Check out this cool website I want to emulate. The site is a single-page design where you can navigate vertically using various methods like keyboard, mouse, scroll, or swipe gestures. There are carousels that allow left and right navigation. Each section ...

Limit the options in jQuery UI auto-complete to search by name from a variety of JSON responses

I am looking to enhance my search functionality by utilizing jqueryUi's auto-complete feature to specifically target Names and exclude other array values such as fax. Here is how I have implemented it in php: <?php require_once 'db_conx.php&a ...

Whenever I attempt to connect to Stripe, my code fails to execute properly

My knowledge of Javascript is limited, but I have a basic understanding. I am currently diving into learning about Stripe and testing it in a local environment with a Wordpress install. Following the Stripe documentation, I have successfully installed Node ...

How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServ ...

Leveraging ng-change in AngularJS when utilizing the "Controller As" syntax

Attempting to steer clear of using $scope within my controller function, I have instead chosen to use var viewModel = this; employing the "controller as" viewModel syntax. The issue at hand is that while I can access data from a service, invoking functio ...