Reputation: 1119
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?
Upvotes: 4
Views: 4274
Reputation: 169401
To overwrite the way models are saved and loaded from the database you can overwrite two Methods.
Model.toJSON
place custom serialization logic here.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
Upvotes: 8
Reputation: 5955
I think your idea to overwrite the sync method is exactly right. toJSON should always return JSON, if it returned something other than JSON, other programmers might find it difficult to understand your code.
Upvotes: 0