Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defineProperty on Backbone model

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.

like image 992
homtg Avatar asked Nov 11 '13 13:11

homtg


1 Answers

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:

  • Backbone.ModelMorph
  • Backbone.ComputedModel
  • Backbone.Spark
  • Backbone.ComputedFields
like image 179
Peter Lyons Avatar answered Oct 22 '22 02:10

Peter Lyons