Search code examples
javascriptbackbone.js

How can I enforce attribute types in a Backbone model?


I want to have a Backbone model with float attributes in it but without worrying too much about variable types.

I would like to encapsulate the value parsing right there in the model so I am thinking of overriding the set function:

var Place = Backbone.Model.extend({
  set: function(attributes, options) {
    if (!_.isEmpty(attributes.latitude)){
      attributes.latitude == parseFloat(attributes.latitude);
    }
    if (!_.isEmpty(attributes.longitude)){
      attributes.longitude == parseFloat(attributes.longitude);
    }
    Backbone.Model.prototype.set.call(this, attributes, options);
  }
});

However this seems cumbersome, since I would have a similar logic in the validate method and potentially repeated across multiple models. I don't think the View should take care of these conversions.

So what is the best way of doing it?


Solution

  • Use a validation plugin for your model so that you can validate the input in a generic fashion.

    There are several out there including one that I have written:

    Then you don't worry about performing data validation anywhere else - your model does it and sends out and error message you can listen for and provide appropriate feedback.

    Also, a lat/lng pair can, in rare circumstances, be an integer, such as Greenwich England: 0,0 or the north pole: 90,180. And since JavaScript only has "number" any valid input for parseFloat is also valid for parseInt.

    But parseFloat will always return a float.