skip to Main Content

I have a dialog in my html with id="divMyDialog1". This is associated with a javascript class with a name MyDialog1. (These names are just for illustration only.)

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

I have loads of these dialogs and associated classes. What I would like to do is set up all these different string ids and associate them with their dialog class. Some Dialog Classes would have multiple instances but with different divStr.

But how would this be done?

I want something on the lines:

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

2

Answers


  1. You could just have:

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

    And then initialize dialogs like this into the array:

    let dialogARR = [];
    
     [new Dialog("divMyDialog1", "MyDialog1"), new Dialog("divMyDialog2", "MyDialog2")].forEach(o => dialogARR.push(o));
    

    That’s how I would go about it, please correct me if I’m wrong.

    Login or Signup to reply.
  2. Loop through the array, extracting the properties from each object and then calling the class constructor function with new.

    dialogArr.forEach(({divStr, className}) => new className(divStr));
    

    If you need the instances, you can use .map() instead of .forEach(), and it will return an array of the instances.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search