Reputation: 1999
If i want to add a custom property to my backbone model, is this the best was 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 just "virtual", i do not want it to be within the model attributes when saving the model to the server.
Upvotes: 7
Views: 541
Reputation: 524
When you set your property to defaults oject, it goes to attributes, but it doesn't suit us. Since Backbone model is an regular object, you can access to it's properties as to objects properties:
var myModel = Backbone.Model.extend({}),
model = new myModel();
model.monthly_amount = 50;
console.log(model.monthly_amount)
or create setter and getter like this:
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);
Upvotes: 0
Reputation: 146084
So the general problem here is often referred to as "computed properties" and there are plugins for backbone that provide this (see below). Backbone uses get/set
method calling style as opposed to defineProperty
style so your approach would make the value computation not transparent to views and thus be a pretty strong departure from backbone's design. A plugin that maintains the proper get/set
and change
interfaces is going to maintain the basic Model API so the view doesn't have to treat this particular model attribute differently.
See also the backbone wiki of plugins.
Available plugins:
Upvotes: 2