When I fetch models or collections from the server, I am not able to access properties of the model unless I stringify then re-parse. Presumably the models themselves have some extra overhead from backbone.js? Note that in the below code I can perform stringify/parse sequentially, which is supposed to give the same result as I started with. However, clearly I have killed off some superfluous info by performing these two steps because my model’s properties are now exposed differently from before. Surely I do not need to go through these two steps to access my model properties, right?
Eg.
thismodel = /// assume this came from server fetch
alert(thismodel.name); // DOES NOT WORK - undefined
jsonmodel = JSON.stringify(thismodel);
var providerprefslistJSON = jQuery.parseJSON(jsonmodel);
alert(providerprefslistJSON.name); // WORKS
Backbone Model objects are not plain old JavaScript objects. They keep their attributes in an internal hash. To access the
nameattribute you can either do this:alert(thismodel.attributes.name);Or better yet use the get() method:
alert(thismodel.get("name"));The reason it works when you convert the model to JSON and then back again is because
JSON.stringifycalls the toJSON() method, which creates a JSON string from the internal attributes hash, meaning when you parse that string you get a plain old JavaScript object – which is not the same as a Backbone Model object.