Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Modifying data in model before save

I was wondering how I would go about converting data when I call the set or save methods on a model. Specifically converting the inputted date string to epoch time.

I know I could just convert it in the view, but as far as I know, that wont work very well with my validations.

The model code is here if you are interested.

Thanks for any help!

like image 718
Tom Brunoli Avatar asked Aug 30 '26 04:08

Tom Brunoli


1 Answers

What I can gather you have two options:

1 Convert them in your view

This means you can roll your own conversions for the view or use something like Backbone.modelbinder to make the conversions for you. Then you have to modify your validate method to accept an epoch date. Personally I would prefer this one, I think that it's suitable for the UI to handle verifying user input's well-formedness and conversion to the right unit and let the model handle validating if the values are within the accepted limits.

2 Convert them in your model

Backbone doesn't offer this out-of-the-box. If you set something to be something, there is no easy way to convert it to something else, especially between validate and set. Basically your best bet would be to roll your own set -function with something like

// Inside the set function
...
if (!this._validate(attrs, options)) return false; // real line in the set func
// insert something like this, after validate you know the values are eligible for conversion
attrs = this.convert(attrs); // a custom func that converts attributes to right units
...
// set continues as usual

Hope this helps!

like image 125
jakee Avatar answered Aug 31 '26 17:08

jakee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!