Backbone.js serializes model attributes for synchronization

I am trying to save a rather complex model, including inline collections, into a relational database. Thanks to the built-in collections, the data returned to the server contains objects that are fairly fair. However, I am building a basic application on top of an existing application and must return the values ​​in scalar form in order to be able to reuse the code on the server side. What works best for this, I was thinking of redefining the model for the JSON function, but I really don't feel what it should be. So another alternative that I can think of is to overwrite the synchronization method and do it there. However, even this does not seem correct. Am I missing something or rewriting the synchronization method to the right evil?

+4
source share
2 answers

To overwrite the way you save and load models from the database, you can overwrite two methods.

  • Model.toJSON place serialization logic logic here.
  • Model.parse post a special de-serialization logic here.

Ideally, you only have custom serialization / de-serialization logic to “optimize” the database. That is, if you have an Age and DateOfBirth , you save it only in the database in Model.toJSON and calculate the other in Model.parse .

If you need a special serialization / de-serialization logic that is NOT intended for the model, rewrite Backbone.Sync .

You can also overwrite model.Sync . This means that the model will use the custom Sync custom function and then use Backbone.Sync

+8
source

I think your idea of ​​rewriting the synchronization method is exactly right. toJSON should always return JSON if it returns something other than JSON, it might be difficult for other programmers to understand your code.

0
source

All Articles