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?
I am trying to save a fairly complex model including embedded collections back to
Share
To overwrite the way models are saved and loaded from the database you can overwrite two Methods.
Model.toJSONplace custom serialization logic here.Model.parseplace custom de-serialization logic here.Ideally you only have custom serialization / de-serialization logic to “optimise” the database. I.e. if you have an
AgeandDateOfBirthfield you only store one in the database inModel.toJSONand calculate the other inModel.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 customSyncfunction rather then usingBackbone.Sync