Sachin Jain
Sachin Jain

Reputation: 21842

Creating new model in backbone?

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.

1. This works fine

var mapModel = {
  'one': M1,
  'two': M2
};

new mapModel['two']();

2. Does not work

var model = new (getModel('two')());
var model = (new getModel('two'))();

I do not understand what is undefiend and why I am seeing this error.

Upvotes: 3

Views: 110

Answers (3)

Evan Sebastian
Evan Sebastian

Reputation: 1744

How about wrapping new operator in this factory function?

function createModel() {
  var object = new (arguments[0]);
  (arguments[0]).apply(object, [arguments[1]]);
  return object;
}

var model = createModel(getModel('two'));
var model2 = createModel(getModel('two'), { value: 4 });
console.log(model.get('value')); // 2
console.log(model2.get('value')); // 4

Edit You can also combine the factory method with your current getModel

var getModel = function() {
   var map = {
     'one': M1,
     'two': M2
   };
   var type = arguments[0];
   var M = map[type];
   var obj = new M;
   M.apply(obj, [arguments[1]]);
   return obj;
};
var model = getModel('two');
console.log(model.get('value')); // 2
var model2 = getModel('two', { value : 4});
console.log(model2.get('value')); // 4

Upvotes: 0

Evgeniy
Evgeniy

Reputation: 2921

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

Upvotes: 1

Sachin Jain
Sachin Jain

Reputation: 21842

I have got the reason, I was facing the issue. Let's understand the mistakes one by one. Working JSbin

We need to fully understand the precedence of new operator.

Sample #1

var model = new getModel('two')();

In this case, new is used with getModel method and we try to again call what is being returned by new getModel('two).

Sample #2, #3

var model = new (getModel('two')());
var model = (new getModel('two'))();

In these cases, whatever is returned from getModel('two') is called first and then instance is created.

Solution

var model = new (getModel('two'))();

Upvotes: 0

Related Questions