Been getting into Knockout and and slowly getting used to it. Trying to use it in a new project, but am having a hard time getting things lined up to work. While I understand and can do simple examples (simple form with text boxes bound to ko.observables, or a table or list bound to a ko.observableArray), I can’t get the syntax right for a combination, especially if I want to convert the data to JSON format in order to transmit it, via a webservice, to be saved into a database.
Basically it’s a data entry form, with some text entry boxes, then a list of items (think company information + a list of it’s employees).
I have a sample Fiddle here: http://jsfiddle.net/rhzu6/
In the saveData function, I just don’t know what to do to get the data packaged. Doing ko.toJS(self) just shows “Object”.
I tried defining the data as objects, but quickly got lost:
function Company(CompanyName, ZipCode) {
var self = this;
self.ZipCode = ko.observable(ZipCode);
self.CompanyName = ko.observable(CompanyName );
self.Employees = ko.observableArray();
}
function Employee(FirstName, LastNameB) {
var self = this;
self.FirstName = ko.observable(FirstName);
self.LastName = ko.observable(LastName);
}
Then the ViewModel looked like:
function viewModel() {
var self = this;
self.Company = ko.observable(); // company?
self.Employees = ko.observableArray(); // ?
}
But ran into the same issue. And also had binding problems – data-bind:”value: CompanyName” threw an exception saying it didn’t know what CompanyName was…
Color me stumped. I’m sure it’s something easy that I’m just missing.
Any and all help would be appreciated!
Thanks
You are looking for
ko.toJSONwhich will first call ko.toJS on your ViewModel and afterwardsJSON.stringify.ko.toJSwill convert your knockout model to a simple JavaScript object, hence replacing all observables etc. with their respective values.I updated your Fiddle to demonstrate.
For more info, take a look at this post from Ryan Niemeyers blog.
An alternative is to make use of
ko.utils.postJson:Notice the
ko.toJSagain.