JSON.stringify () with collection in backbone.js

Can someone explain how JSON.stringify () magically ONLY builds JSON as selectable by URL and doesn't worry about other parts of the specific part of the complete collection object?

I am curious about the basic implementation and / or design options that explain this very impressive feature. I had to use json2.js to get stringify functionality, so I don't think the framework is overriding or decorating stringify.

I found that if I pass the collection directly to the JS OBJECT code, the code β€œsees” the model keys and other parts of the collection object part related to the base, whereas if I execute JSON.stringify THEN jquery.parseJSON on this gated object, my code β€œsees” "only JSON returned by URL.

code:

enter code here $(function () { var Person = Backbone.Model.extend({ initialize: function () { // alert("Model Init"); } }), PersonList = Backbone.Collection.extend({ model: Person, url: '/Tfount_Email/Email/SOAInbox', initialize: function () { // alert("Collections Init"); } }), personlist = new PersonList(); personlist.fetch({ error: function () { alert("Error fetching data"); }, success: function () { // alert("no error"); } }).complete(function () { // first call to makeTable w collection obj, we see MORE than just the JSON returned by URL makeTable(personlist); // stringify then parse, we see only JSON returned by URL jsonString = JSON.stringify(personlist); var plistJSON = jQuery.parseJSON(jsonString); makeTable(plistJSON); }); }); function makeTable(obj) { var type = typeof obj if (type == "object") { for (var key in obj) { alert("key: " + key) makeTable(obj[key]) } } else { alert(obj) } } 
+4
source share
1 answer

This is the intentional and standard behavior of JSON.Stringify . From the Douglas Crockford JSON2.js file:

When the value of the object is found, if the object contains the toJSON method, its toJSON method will be called and the result will be wired.

https://github.com/douglascrockford/JSON-js/blob/master/json2.js#L38-39

When you call JSON.stringify on Backbone.Collection, it calls this toJSON collection toJSON , as described in this comment.

+11
source

All Articles