When testing and debugging your web-application, its convenient to see the real-time state of the view-model. This is very easy when you’re using a data-binding framework such as knockout. You can simply bind the JSON representation of the view-model to some visible DOM element, like this:
<pre data-bind="text: JSON.stringify(ko.toJS(MyViewModel), null, 4)"></pre>
Sometimes, the objects in your view-model might have circular dependencies, like this:
//The ViewModel var CurrencyViewModel = function () { var self = this; this.DataContext = new CurrencyDataContext(this); this.Name = ko.observable(); ... } //The pseudo-model behind the ViewModel var CurrencyDataContext = function CurrencyDataContext(ViewModel) { var self = this this.Viewmodel = ViewModel ... }
In that case you’ll get the following error:
0x800a13aa - JavaScript runtime error: Circular reference in value argument not supported
You can fix this by overriding the toJSON()
method, like this:
var CurrencyDataContext = function CurrencyDataContext(ViewModel) { var self = this this.Viewmodel = ViewModel ... //Needed to avoid circular reference when a viewModel is serialised into JSON CurrencyDataContext.prototype.toJSON = function () { var copy = ko.toJS(self); delete copy.Viewmodel return copy; }