This is my first time using knockout. I'm reading/writing a JSON file with a fair bit of nested data. I had no problem creating the ViewModel to just write to the file, but now that I'm reading the data into my model also, I've had to write a few if/else statements to handle the different cases. Not sure if this is the right way to do it.
I've got a ViewModel with a function to add a new record, and to save the data. The 3 functions above are used for mapping the data.
function Survey(name, panes, tester)
{
this.name = ko.observable(name);
this.panes = ko.observableArray([new Pane(panes)]);
this.tester = ko.observable(tester);
}
function Pane(panes)
{
//var panesCount = panes.length;
//console.log(panes[0].type);
if (panes) {
this.type = ko.observable(panes[0].type);
this.head = ko.observable(panes[0].head);
this.content = ko.observable(panes[0].content);
this.options = ko.observableArray([new PaneOptions(panes[0].options)]);
}
else {
this.type = ko.observable();
this.head = ko.observable();
this.content = ko.observable();
this.options = ko.observableArray([new PaneOptions()]);
}
}
function PaneOptions(options)
{
//console.log(options);
if (options) {
this.data = ko.observable(options[0].data);
this.target = ko.observable(options[0].target);
}
else {
this.data = ko.observable();
this.target = ko.observable();
}
}
function SurveyViewModel()
{
var self = this;
self.surveys = ko.observableArray([]);
$.getJSON("create/fetch", function(data) {
//console.log(data.surveys[0].name);
if (data) { // check if json file is empty
for (var i=0; i < data.surveys.length; i++) {
console.log(i);
self.surveys.push(new Survey(data.surveys[i].name, data.surveys[i].panes, data.surveys[i].tester))
}
}
});
self.addSurvey = function ()
{
self.surveys.push(new Survey());
};
self.saveUserData = function()
{
var data_to_send = ko.toJSON(self);
$.post("create/save", data_to_send, function(data) {
console.log("Your data has been posted to the server!");
});
}
}
var vm = new SurveyViewModel();
ko.applyBindings(vm);
Here you can see the JSON representation:
{
"surveys": [
{
"name": "My First Survey1",
"panes": [
{
"type": "question1",
"head": "Heading Text1",
"content": "multichoice1",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default"
},
{
"name": "My Second Survey2",
"panes": [
{
"type": "response2",
"head": "Heading Text2",
"content": "multichoice2",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default2"
},
{
"name": "My Third Survey3",
"panes": [
{
"type": "thanks3",
"head": "Heading Text3",
"content": "multichoice3",
"options": [
{
"data": "Time",
"target": 2
}
]
}
],
"tester": "default3"
}
]
}
Any input is greatly appreciated!