I want to create a new model based on some parameter. JSBin Demo
var M1 = Backbone.Model.extend({
defaults: { type: 'one', value: 1 }
});
var M2 = Backbone.Model.extend({
defaults: { type: 'two', value: 2 }
});
var getModel = function(type) {
var map = { 'one': M1, 'two': M2 };
return map[type];
};
// Error in this line (Undefined is not a function)
var model = new getModel('two')();
console.log(model.get('value'));
I have tried several notations but could not pin-point the reason.
var mapModel = {
'one': M1,
'two': M2
};
new mapModel['two']();
var model = new (getModel('two')());
var model = (new getModel('two'))();
I do not understand what is undefiend and why I am seeing this error.
I think it this case is better to update getModel function and delegate it creating model instances.Lets create factory from getModel
var getModel = function(type) {
var map = { 'one': M1, 'two': M2 };
return new map[type];
};
Then you can use it to get new instance of proper type model:
var model = getModel('two');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With