0

I'd like one of my getters to return a minimum value of the model's collection, is it possible to have a model getter function? Reason I need this is so I can easily have my models rendered in a template using toJSON.

el_pup_le
  • 11,711
  • 26
  • 85
  • 142
  • look into the min method that comes with underscore.js http://underscorejs.org/#min – Rohit Nov 19 '13 at 16:46
  • have you seen [the post](http://stackoverflow.com/questions/10147969/saving-jquery-ui-sortables-order-to-backbone-js-collection) – Ulug'bek Nov 19 '13 at 17:27

2 Answers2

0

Are these minimum values just defaults to fill in, if there is nothing else?

If so. you can define the defaults on the model

var model = Backbone.Model.extend({
    defaults: {
        attrA: 'attr a default',
        attrB: 'attr b default'
    }
});
Alex Curtis
  • 5,659
  • 3
  • 28
  • 31
  • not defaults, at any given time i'd like to be able to get a value based on some criteria via getter, ie a getter as a function – el_pup_le Nov 19 '13 at 13:26
0

Apart from the defaults you can override the get method if you need more control.

var MyModel = Backbone.Model.extend({
   get: function (attr) {
      if (attr === 'my_attribute')
      {
         return this.getMyAttribute();
      }

      return Backbone.Model.prototype.get.call(this, attr);
   },
   getMyAttribute: function() {
      var result = Backbone.Model.prototype.get.call(this, attr);
      if (typeof result === "undefined" || result < 0) return 0;
      return result;
   }
});
Markinhos
  • 736
  • 1
  • 6
  • 13