[英]dynamically created javascript object
我有一种情况,我需要通过“ New”关键字声明一个新的主干模型。 但是创建的模型类型由用户确定(下拉列表)。
代码如下:
var type = $(".typeSelector option:selected").val();
var subType = 'subType' + "." + $(".typeSelector option:selected").attr("subType");
console.log(type); //correct
console.log(subType); //correct
$('#form1').append(new MyView({ model: new this.type({ subType: subType }) }).render().$el);
这是.typeSelector下拉列表:
<select class="typeSelector">
<option value="rotary">Rotary</option>
<option subType="iron" value="Xgear">Iron X Gear</option>
<option subType="steel" value="Xgear">Steel X Gear</option>
<option value="wormDrive">Worm Drive</option>
</select>
它可以正确地写到控制台,但是不喜欢我形成对象的方式,并且在Firebug中给了我这个错误:
TypeError:类型不是构造函数
根据模型作用域的范围,可以使用window [typeName]等引用它。
return new window[ type ]()
http://jsfiddle.net/8aFpU/上的简单幼稚jsFiddle
我想说,做您需要的一个好方法是替换这段代码:
model: new this.type({ subType: subType })
通过函数调用:
model: getCorrectType(type, subType)
然后,在函数中可以确定所需的正确实例:
function getCorrectType(type, subType) {
if (type === 'rotary') {
return new Rotary(); //the correct name of your model
}
if (subType === 'iron') {
return new Iron();
}
if (subType === 'steel') {
return new Steel();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.