DefineProperty on the base model

If I want to add a custom property to my base model, is it better to do this? Is there a better way or a completely different approach to the functionality I want to achieve?

var myModel = Backbone.Model.extend({ defaults:{ monthly_amount: 100 }, initialize: function(model, options){ var m = this; Object.defineProperty(this,"yearly_amount",{ get: function() { return (m.get("monthly_amount") * 12); }, set: function(value) { m.set("monthly_amount", (value/12) ); } }); } }); 

Thanks!

Edit: the property is "virtual"; I do not want it to be in the model attributes when saving the model to the server.

+7
javascript
source share
2 answers

Thus, a common problem here is often referred to as “computed properties”, and there are plugins for the trunk that provide this (see below). Backbone uses the call method of the get/set method, and not the defineProperty style, so your approach will make calculation calculations opaque to view, and thus will become a pretty strong departure from the basic design. A plugin that supports the correct get/set and change interfaces will support the base model API, so the view should not handle this particular model attribute differently.

See also the basic plugin wiki .

Available plugins:

+2
source share

When you set the default property to default, it goes over to the attributes, but that doesn't suit us. Since the Backbone model is a regular object, you can get properties of the properties of objects to it:

 var myModel = Backbone.Model.extend({}), model = new myModel(); model.monthly_amount = 50; console.log(model.monthly_amount) 

or create the setter and receiver as follows:

 var myModel = Backbone.Model.extend({ setMonthlyAmount: function (value) { this.monthly_amount = value; }, getMonthlyAmount: function () { return this.monthly_amount; } }); //access with getter/setter var model = new myModel(); model.setMonthlyAmount(20); var result = model.getMonthlyAmount(); console.log(result); 

Working example in jsfiddle

0
source share

All Articles