Reputation: 387
In backbone.js I can initialize a model with
var model = new MyModel();
But I would like to initialize a model with a dynamic name - like "MyDynamicModel". How can I achieve this?
Upvotes: 1
Views: 86
Reputation: 11
If your models are declared globally (on the window
object), then you can use the square bracket notation:
var Model = window[modelName]; // Assuming modelName is the dynamic name of your model
var model = new Model();
Or, if your models are namespaced under something like App.Models
:
var Model = App.Models[modelName];
var model = new Model();
As a last resort, you can use Javascript's eval
function, but in general this should be avoided.
var Model = eval(modelName);
var model = new Model();
Upvotes: 1
Reputation: 485
You can use a wrapper object to get somewhat similar outcome.
var wrapper = {
"myDynamicName": new MyModel(),
"myOtherModel": new MyModel()
}
Then you can call it like this:
wrapper["myDynamicName"].render();
Upvotes: 0