Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify() with collection in backbone.js

Tags:

backbone.js

Can someone explain how JSON.stringify() magically ONLY stringifies JSON as fetched by URL and does NOT bother with other backbone-specific parts of the full collection object?

I am curious about underlying implementation and/or design patterns that explain this very impressive capability. I had to use json2.js to get stringify functionality, so I don't think backbone is overriding or decorating stringify.

I discovered that if I pass a collection directly to JS OBJECT code, the code "sees" model keys and other backbone-specific parts of a collection object, whereas if I perform JSON.stringify THEN jquery.parseJSON on that stringified object, my code "sees" only the JSON as 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)
    }

}
like image 945
goldfinger Avatar asked Dec 21 '22 17:12

goldfinger


1 Answers

This is the intended and by-design behavior of JSON.Stringify. From Douglas Crockford's JSON2.js file:

When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified.

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

When you call JSON.stringify on a Backbone.Collection, it calls that collection's toJSON method, as described by this comment.

like image 174
Derick Bailey Avatar answered Dec 28 '22 06:12

Derick Bailey