Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When extending a backbone model or view, how can i create properties that get created on the instance and not on the prototype?

I want to do:

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

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

as if i had done

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

I dont want to put the assignment this.someProp = {...}; in the initialize method because if i subclass MyModel, i ll have to repeat the assignment also in the subclass's initialize method again or remember to call the parents initialize from the children initialize every time i subclass, which it seems to me as a workaround rather than a solution. So, is there any other way?

like image 424
Paralife Avatar asked Jan 20 '12 15:01

Paralife


People also ask

What is backbone view extend?

The Backbone. js view extend method is used to extend the Backbone. js view class to create a custom view. Syntax: Backbone.

What is El property of backbone JS view?

The Backbone. js View el method defines the element that is used as the view reference. this. el is created from the view's tagName, className, id and attributes properties, if specified.

What is backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

If you want to use it for multiple models, then one solution would be to create a standalone function that takes care of it, then you can call that function from the model's initialize method.

Here's 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 isn't any different than having the property assignments in the parent and having the child call the parent's initialize method. And there is less code 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);
  }
});

Unless you want to repeat the property assignments in each initialize method, this is really the only other way to do it in Javascript.

like image 152
Paul Avatar answered Sep 17 '22 23:09

Paul