英文:
A Dialog Controller
问题
我在我的HTML中有一个对话框,其id
为"divMyDialog1"
。这与一个名为MyDialog1
的JavaScript类相关联。(这些名称仅用于说明。)
MyDialog1 = function(divStr){
this.divStr = divStr;
...
}
我有很多这些对话框和相关的类。我想要做的是设置所有这些不同的字符串id
,并将它们与它们的对话框类关联起来。某些对话框类可能会有多个实例,但具有不同的divStr
。
但如何实现这一点?
我希望实现类似以下的效果:
let dialogARR = [];
[{divStr: "divMyDialog1", className: MyDialog1},
{divStr: "divSomethingElse", className: DialogWibble},
{divStr: "divPingPong", className: DialogWobble}].forEach(o => dialogARR.push(new o.className(o.divStr)));
英文:
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 id
s 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)));
答案1
得分: 1
以下是翻译好的部分:
你可以这样做:
class Dialog(){
Constructor(name, class){
this.name = name;
this.class = class;
}
}
然后像这样初始化对话框并放入数组中:
let dialogARR = [];
[new Dialog("divMyDialog1", "MyDialog1"), new Dialog("divMyDialog2", "MyDialog2")].forEach(o => dialogARR.push(o));
这是我会处理的方式,如果我错了,请纠正我。
英文:
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.
答案2
得分: 1
循环遍历数组,从每个对象中提取属性,然后使用new
调用类构造函数。
dialogArr.forEach(({divStr, className}) => new className(divStr));
如果需要实例,可以使用.map()
代替.forEach()
,它会返回实例的数组。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论