SkyeBoniwell
SkyeBoniwell

Reputation: 7092

dynamically created javascript object

I have a scenario where I need to declare a new backbone model via the "New" keyword. But the type of model created is determined by the user(drop down list).

The bit of code looks like this:

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);

Here is the .typeSelector drop down:

<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>

It is writing out to the console correctly, but it doesn't like the way I formed the object and gives me this error in Firebug:

TypeError: type is not a constructor

Upvotes: 0

Views: 58

Answers (2)

Alberto Montellano
Alberto Montellano

Reputation: 6246

I would say that a good way to do what you need is to replace this section of code:

model: new this.type({ subType: subType })

by a function call:

model: getCorrectType(type, subType)

Then, in the function you can determine the correct instance you need:

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();
    }
}

Upvotes: 1

Joe Rinehart
Joe Rinehart

Reputation: 763

Depending on where your model is scoped, you can refer to it with window[typeName] or the like.

return new window[ type ]()

Simple childish jsFiddle at http://jsfiddle.net/8aFpU/

Upvotes: 3

Related Questions