I know this has been asked before a couple of times but I still can't quite find a solution to this issue. (I've only begun using KO 2 weeks ago.)
I have a bunch of fields that are each bound to observables in my VM. When the user clicks the GO button, I want to convert all the fields entered into a JSON string and send to server. This is the ViewModel:
function ViewModel() {
var self = this;
function searchVar() {
self.users = ko.observable();
self.fromdate = ko.observable();
self.todate = ko.observable();
self.eqpname = ko.observable();
self.maker = ko.observable();
self.model = ko.observable();
self.makercode = ko.observable();
self.partname = ko.observable();
self.vendor = ko.observable();
}
self.searchVars = ko.observableArray();
self.addSearchVar = function (vm) {
self.searchVars.removeAll();
self.searchVars.push(vm);
//console.log(vm);
var data = ko.toJSON(self.searchVars);
alert(data);
};
var sv = new searchVar(); //not really using this
}
var vm = new ViewModel();
The problem here is that the addSearchVar function creates a reference to the searchVars array again and this is what creates the circular reference error (have I phrased this right?). Is there a better way to do this? (have tried using a nested model but can't quite wrap my head around it).
The markup is pretty much standard. data-bind:"value: [fieldname]"
and so forth. I placed my ko.applyBindings(vm)
right at the bottom of the page since I have lot of dynamically created components. The button properties are: <input type="button" id="btnGo" value="Go" style="background-color:#CCFFCC" data-bind="click: addSearchVar" />
Appreciate any insights. Thanks. /aj
You can prevent this from happening by removing / replacing the circular references right before you json encode your viewmodel. One way to do this is using Douglas'
JSON.decycle
:https://github.com/douglascrockford/JSON-js/blob/master/cycle.js
This replaces all the circular references with a reference value.
In your case you'd use it like this:
Another option is to remove all the cirular references:
And then: