If I JSON.stringify a backbone model with nested collections/models, send it via websockets to another backbone client and JSON.parse the mode model = JSON.parse(model) will the variable model work just as it did on the other client?
If I JSON.stringify a backbone model with nested collections/models, send it via websockets to
Share
No.
Perhaps I will elaborate. When I do this:
I end up with a simple object in
o. Why? Well, first of all,JSON.parse()doesn’t know anything about non-primitive types (where Array and Object are considered primitive) and in particular, it doesn’t know what a Backbone model is so it can’t rebuild one. Furthermore,JSON.stringifywill call thetoJSONmethod on its argument (if it has one of course) and Backbone supplies atoJSONthat simply returns a copy of the model’s attributes as a simple (possibly nested) object. So once you have the output fromJSON.stringify(model), there is no connection at all between the string and the model, you just have a plain old serialized JavaScript object.If you want to move a Backbone model from one system to another, I think you’d have to track all the model type and object information yourself and then rebuild your serialized piece of the object graph by hand on the other side.
You’d probably be better off saving the model back to its URL, sending the ID to the other Backbone client, and then reload it from the model’s URL as usual. JSON is for serializing data, not objects, interpreting the data as objects is left up to the application.