Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js serializing the models attributes for syncing

I am trying to save a fairly complex model including embedded collections back to a relational database. Due to the embedded collections The data returned to the server contains objects which is fair enough. I am however building the backbone app on top of an already existing application and have to return the values in scalar form to be able to re-use the server side code. What is the best of going about this, I was thinking of overriding the model's toJSON function however I don't really feel like it should be. So the other alternative that I can think of is to overwrite the sync method and do it there. However even that doesn't seem right. Am I missing something or is overwriting the sync method a necessary evil?

like image 876
luxerama Avatar asked Feb 23 '23 18:02

luxerama


1 Answers

To overwrite the way models are saved and loaded from the database you can overwrite two Methods.

  1. Model.toJSON place custom serialization logic here.
  2. Model.parse place custom de-serialization logic here.

Ideally you only have custom serialization / de-serialization logic to "optimise" the database. I.e. if you have an Age and DateOfBirth field you only store one in the database in Model.toJSON and calculate the other in Model.parse.

If you need custom serialization / de-serialization logic that is NOT model specific then overwrite Backbone.Sync.

You can also overwrite model.Sync. This means the model will use a specific custom Sync function rather then using Backbone.Sync

like image 110
Raynos Avatar answered Mar 05 '23 22:03

Raynos