简体   繁体   中英

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?

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. Ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM