Transporting backbone.js models?
If I JSON.stringify a backbone model with nested collecti开发者_开发知识库ons/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?
No.
Perhaps I will elaborate. When I do this:
var o = JSON.parse(JSON.stringify(model));
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.stringify
will call the toJSON
method on its argument (if it has one of course) and Backbone supplies a toJSON
that simply returns a copy of the model's attributes as a simple (possibly nested) object. So once you have the output from JSON.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.
I know backbone maintains an internal id for each of its objects so if you are transferring them like you suggested I don't know how it could work without the possibility of conflict or duplicate cid's.
From backbone's website:
A special property of models, the cid or client id is a unique identifier automatically assigned to all models when they're first created. Client ids are handy when the model has not yet been saved to the server, and does not yet have its eventual true id, but already needs to be visible in the UI. Client ids take the form: c1, c2, c3 ...
EDIT:
After reading 'mu is too short' answer I agree with his answer, but to add some explaination to his comment he left below that I found very informative. Because the backbone.js model has a toJSON() function, when you call JSON.stringify(model) it doesn't parse out all the properties like you would expect, it only parses the object that is returned by the toJSON() method. Excellent answer for 'mu is too short'.
MDN Info JSON.stringify(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify
精彩评论