When expanding a base model or view, how can I create properties that are created on the instance, and not on the prototype?

I want to make:

var MyModel = Backbone.model.extend({ someProp: { ... }, . . }); 

but new MyModel().someProp === new MyModel().someProp return false

as if i did

 function MyModel() { this.someProp = {...}; } 

I do not want to put the destination this.someProp = {...}; to the initialize method, because if I subclass MyModel, I will have to repeat the assignment also in the subclass initialization method again or don't forget to call the parents initialization from the children initialization every time I subclass which seems to me to be a workaround and not a solution. So is there any other way?

+7
source share
2 answers

If you want to use it for several models, then one of the solutions would be to create an autonomous function that takes care of it, then you can call this function from the model initialization method.

Here is an example

 function addInstanceProperties() { this.someProp = 'hello'; this.otherProp = 'world'; } var Parent = Backbone.Model.extend({ initialize: function() { //have to use 'call' so the context is set to this model addInstanceProperties.call(this); } }); var Child = Parent.extend({ initialize: function() { addInstanceProperties.call(this); } }); 

However, this is no different from having property assignments in the parent and has a child call to the parent initialization method. And the code is less involved.

 var Parent = Backbone.Model.extend({ initialize: function() { this.someProp = 'hello'; this.otherProp = 'world'; } }); var Child = Parent.extend({ initialize: function() { Parent.prototype.initialize.call(this); } }); 

If you don't want to repeat property assignments in every initialization method, this is really the only way to do this in Javascript.

+8
source

I would recommend overriding the constructor of the parent class, instead creating a separate function proposed by Paul.

Thus, if you need a custom initialization function in child functions, the constructor saves the properties of the instance, and you do not need to worry about managing the scope or calling some global function passing in the context of this , etc.

 var Parent = Backbone.Model.extend({ constructor: function(options){ this.someProp = 'hello'; this.otherProp = 'world'; Backbone.Model.prototype.constructor.apply(this, arguments); } }); var child = Parent.extend({ initialize: function(){ // don't need to worry about setting up instance props anymore. // don't need to worry about invoking the overridden init method. } }); 

This is the same idea as Pavel made in the second block of code, except that the constructor is separated from initialization in the trunk for this exact reason - so that you can redefine / configure the initialization actions without having to copy / paste redundant construction options every time, when you do it.

0
source

All Articles