The view model has a circular reference, by design, making the use of <pre data-bind="text: ko.toJSON($data)"></pre> for debugging to throw:
Unable to parse bindings.
Message: TypeError: Converting circular structure to JSON;
Bindings value: text: ko.toJSON($data)
Is there a way to work around this?
It is ultimately the call to JSON.stringify inside of ko.toJSON that causes your error.
One way that you can control the output of your JSON is by supplying a toJSON function on your object as described here: http://www.knockmeout.net/2011/04/controlling-how-object-is-converted-to.html. That way you can remove the circular reference in the appropriate place.
There are a few other techniques that you could use for this as well.
You can pass a second argument to ko.toJSON. This is the replacer option to JSON.stringify as described here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.
For example, you can pass an array of properties to include like:
ko.toJSON(myobject, ["one", "two", "three"])
You can attach a property that you don't want to get turned into JSON as a "sub"-observable like:
this.data = ko.observable();
this.data.parent = parent;
In this case, data will get turned into JSON, but parent will just disappear, as it is a property on an observable that already gets unwrapped into its value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With