I need map this array to observable array.
actionsDataTime = {
"t16082209": [
{
"timeId": "16082209",
"id": 176,
"class_from": "09:00",
"class_to": "10:25",
"action": {
"name": "AQUA",
"color": "aqua",
"icon": ""
},
"trainer": {
"id": 348,
"name": "Art Edition"
},
"capacity": 11,
"capacity_left": 11,
"substitutes": 5,
"substitutes_left": 5,
"price": 1
}
],
"t16082308": [
{
"timeId": "16082308",
"id": 169,
"class_from": "08:00",
"class_to": "09:00",
"action": {
"name": "ZUMBA",
"color": "zumba",
"icon": ""
},
"trainer": {
"id": 210,
"name": "Adam Pt\u00e1\u010dek"
},
"capacity": 10,
"capacity_left": 10,
"substitutes": 5,
"substitutes_left": 5,
"price": 1
}
],
"t16082408": [
{
"timeId": "16082408",
"id": 173,
"class_from": "08:00",
"class_to": "09:05",
"action": {
"name": "KICK BOX",
"color": "box",
"icon": ""
},
"trainer": {
"id": 360,
"name": "Alexandra Galov\u00e1"
},
"capacity": 10,
"capacity_left": 10,
"substitutes": 5,
"substitutes_left": 5,
"price": 2
},
{
"timeId": "16082408",
"id": 175,
"class_from": "08:00",
"class_to": "09:05",
"action": {
"name": "KICK BOX",
"color": "box",
"icon": ""
},
"trainer": {
"id": 360,
"name": "Alexandra Galov\u00e1"
},
"capacity": 10,
"capacity_left": 10,
"substitutes": 5,
"substitutes_left": 5,
"price": 2
}
]
}
Section "t16082308" is some timestamp that I need in app so it is dynamic. Number of actions in array can be changed be too.
I am able to map this by mapping module this way
ko.mapping.fromJS(actionsDataTime, self.actionsData);
but when i need to reload it from server like this
self.reloadActions = function() {
$.ajax({
type: 'GET',
url: {link reloadActions! },
dataType: "json",
success: function(data) {
ko.mapping.fromJS(data, {}, self.actionsData);
}
})
};
and is there a new timestamp section or soma new action - nothing changes in frontend and it looks that not all things are mapped as observables. When I only change some value like "capacity" it works fine.
How can I map it better (all to observables) so I can see change when actions is added or deleted?
This is how I would do it:
var actionObj = function (data) {
this.name = ko.observable();
this.color = ko.observable();
this.icon = ko.observable();
this.update(data);
}
ko.utils.extend(actionObj.prototype, {
update: function (data) {
this.name = ko.observable(data.name || '');
this.color = ko.observable(data.color || '');
this.icon = ko.observable(data.icon || '');
}
});
self.Action = function (data) {
return new actionObj(data);
}
var trainerObj = function (data) {
this.id = ko.observable();
this.name = ko.observable();
this.update(data);
}
ko.utils.extend(trainerObj.prototype, {
update: function (data) {
this.id = ko.observable(data.id || '');
this.name = ko.observable(data.name || '');
}
});
self.Trainer = function (data) {
return new trainerObj(data);
}
var actionsDataTimeObj = function (data) {
this.timeId = ko.observable();
this.id = ko.observable();
this.class_from = ko.observable();
this.class_to = ko.observable();
this.action = ko.observableArray();
this.trainer = ko.observableArray();
this.capacity = ko.observable();
this.capacity_left = ko.observable();
this.substitutes = ko.observable();
this.substitutes_left = ko.observable();
this.price = ko.observable();
this.update(data);
}
ko.utils.extend(actionsDataTimeObj.prototype, {
update: function (data) {
this.timeId = ko.observable(data.timeId || '');
this.id = ko.observable();
this.class_from = ko.observable();
this.class_to = ko.observable();
var _action = $.map(data.action, function (item) {
return new self.Action(item);
});
this.action(_action);
var _trainer = $.map(data.trainer, function (item) {
return new self.Trainer(item);
});
this.trainer(_trainer);
this.capacity = ko.observable();
this.capacity_left = ko.observable();
this.substitutes = ko.observable();
this.substitutes_left = ko.observable();
this.price = ko.observable();
}
});
self.ActionsDataTime = function (data) {
return new actionsDataTimeObj(data);
}
Basically you have to declare your "action" and "trainer" as ObservableArrays and then map the data to them in the update function of the ActionsDataTime object. Then everything will be observables.
Oh, then:
self.actionsData = ko.observableArray();
var _actiondatatimes = $.map(data, function (item) {
return new self.ActionDataTime(item);
});
self.actionsData(_actiondatatimes);
Related
I am trying to create an array that represents three different merchants which hold different prices for the same products(represented later in the code which ones).
My logic seems off and I would like help with one example on how this should be done correctly.
Attached is my code but please take notice only to the Merchantprices and getRecipeItems part.
JS
var main = function () {
var recipeType = {
0: {"name": "cocktail", "ingredients": ["Booz","Roofis","Green Stuff"]},
1: {"name": "appetizer", "ingredients": ["Some leaves","Some veggies", "I dunno toast","Cheese or whatever"]},
2: {"name": "main course", "ingredients": ["A dead animal","its blood", "some potatoes","love","asparagus"]} ,
3: {"name": "dessert", "ingredients": ["Dough","Some Sprinkly shit", "sugar","more sugar","cream shaboogy pop"]} ,
}
var Merchantprices = {
ampm:{"ingredientPrice":recipeType[0].ingredients = 20,"sumPrice":recipeType[0] = ingredientPrice * (recipeType[0].ingredients.length)},
haCarmel:{},
tivTaam:{},
}
function getRecipeItems() {
return recipeItems = [
{
"id": "recipe0",
"title": "Grasshopper Cocktail",
"img": "../images/grasshopper-cocktail.jpg",
"ingredients": recipeType[0].ingredients,
"instructions":"shaken not stirred",
"price": {"ampmPrice":Merchantprices[0].sumPrice,"haCarmelPrice":Merchantprices[1].sumPrice,"tivTaamPrice":Merchantprices[2].sumPrice},
"type" : recipeType[0].name,
},
{
"id": "recipe1",
"title": "Beef roast with veggies",
"img": "../images/beef-roast-with-veggies.JPG",
"ingredients": recipeType[2].ingredients,
"instructions":"stuff it good",
"price": 55,
"type" : recipeType[2].name,
},
{
"id": "recipe2",
"title": "Shrimp-Fried-Rice",
"img": "../images/Shrimp-Fried-Rice.jpg",
"ingredients": recipeType[1].ingredients,
"instructions":"extra MSG",
"price": 65,
"type" : recipeType[1].name,
},
{
"id": "recipe3",
"title": "Cupcake from hell",
"img": "../images/Cupcake-Idea-pics-200x150.png",
"ingredients": recipeType[3].ingredients,
"instructions":"death is inevitable",
"price": 15,
"type" : recipeType[3].name,
},
]
}
function createRecipeItem(recipeItem) {
var recipeElement = document.createElement('div');
recipeElement.setAttribute("id", recipeItem.id);
recipeElement.setAttribute("class", recipeItem);
recipeDetailsElement = document.createElement("div");
recipeDetailsElement.setAttribute("id", recipeItem.id+"_details");
recipeDetailsElement.appendChild(createDeleteRecipe(recipeItem));
recipeDetailsElement.appendChild(createRecipePic(recipeItem));
recipeDetailsElement.appendChild(createRecipeTitle(recipeItem));
recipePreperationElement = document.createElement("div");
recipePreperationElement.setAttribute("id", recipeItem.id+"_full_details");
recipePreperationElement.appendChild(createRecipeIngredients(recipeItem));
recipePreperationElement.appendChild(createRecipeInstructions(recipeItem));
recipePreperationElement.style.display = 'none';
recipeDetailsElement.appendChild(recipePreperationElement);
recipeElement.appendChild(createUndoDeleteRecipe(recipeItem));
recipeElement.appendChild(recipeDetailsElement);
return recipeElement;
}
function createUndoDeleteRecipe(recipeItem) {
var undoButton = document.createElement('span');
undoButton.setAttribute("id", recipeItem.id + "_undo");
undoButton.setAttribute("class", "fa fa-undo", "aria-hidden", "true");
$(undoButton).hide();
$(undoButton).click(() => {
onItemDeleteUndo(recipeItem);
});
return undoButton;
}
function createDeleteRecipe(recipeItem) {
var deleteButton = document.createElement('span');
deleteButton.setAttribute("class", "fa fa-times-circle", "aria-hidden", "true");
$(deleteButton).click(() => {
onItemDelete(recipeItem);
});
return deleteButton;
}
function onItemDelete(recipeItem) {
$('#'+recipeItem.id+'_details').hide();
$('#'+recipeItem.id+'_undo').show();
}
function onItemDeleteUndo(recipeItem) {
$('#'+recipeItem.id+'_details').show();
$('#'+recipeItem.id+'_undo').hide();
}
function createRecipeTitle(recipeItem) {
var div = document.createElement('div');
div.innerHTML = recipeItem.title;
return div;
}
function createRecipeInstructions(recipeItem) {
var div = document.createElement('div');
div.innerHTML = recipeItem.instructions;
return div;
}
function createRecipePic(recipeItem) {
var recipePic = document.createElement("img");
recipePic.setAttribute("src", recipeItem.img);
recipePic.setAttribute("class", "recipe");
$(recipePic).css('margin-top', '10px');
$(recipePic).click(() => {
$('#'+recipeItem.id+"_full_details").slideToggle();
});
return recipePic;
}
function createRecipeIngredients(recipeItem) {
var ingredients = document.createElement("ul");
ingredients.setAttribute("id", recipeItem.id + "_ingredients");
ingredients.className = "ingredientsList";
recipeItem.ingredients.forEach(ingredient => {
var li = document.createElement("li");
li.className = "ingredients";
li.setAttribute("type", "checkbox");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
li.appendChild(checkbox);
var ingredientElement = document.createElement("a");
ingredientElement.innerHTML = ingredient;
li.appendChild(ingredientElement);
ingredients.appendChild(li);
})
return ingredients;
}
recipeItems = getRecipeItems();
var mainContainer = document.getElementsByClassName('mainContainer');
recipeItems.forEach(recipeItem => {
mainContainer[0].appendChild(createRecipeItem(recipeItem));
});
};
var recipeItems;
var Merchantprices;
$(document).ready(main);
Ok, so I think I got want you meant to do. Here are 2 solutions :
Keep all in one place
function getRecipeItems() {
return recipeItems = [
{
"id": "recipe0",
// ...
"price": {
default: 8,
ampm: 10,
// -- haCarmel: 12, -- Let's omit this one
tivTaam: 15,
get: function( merchant ) {
return this[merchant] ? this[merchant] : default;
}
}
},
// ...
]
}
// ---------------------------------------
// Usage
// ---------------------------------------
// Result : 8 (default price, as you didn't specify the merchant).
getRecipeItems()[0].price.get();
// Result : 10.
getRecipeItems()[0].price.get("ampm");
// Result : 8 (default, as you didn't set this value).
getRecipeItems()[0].price.get("haCarmel");
Merchant's magic calculations
You could also set a default price, but send it to the merchant and alter it.
// Price
"price": {
default: 8,
get: function( merchant ) {
return Merchants[ merchant ]
? Merchants[ merchant ].getPrice( this.default )
: this.default;
}
}
// Merchants
Merchants {
ampm: {
//...
getPrice: function( price ){
return price + itemRarity - discount + etc;
}
},
// ...
};
In both cases, ...
You should create an object for the Merchant, RecipeItem and RecipeItemPrice. Your code will be more clean and you wouldn't create an instance of the get() function each time you create a price. Well, you should do that with ALL your game objects. :)
// Price
var RecipeItemPrice = function( value, ... ) {
this.default = value;
};
RecipeItemPrice.prototype.get = function() {
// For example, if you take the second choice :
return Merchants[ merchant ]
? Merchants[ merchant ].getPrice( this.default )
: this.default;
};
I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);
I have an issue about checking for an existing product in knockoutjs.
The problem is: if the product exists in Cart Line, the product quantity will increase, if not, it will be added to Cart
This is code:
var CartLine = function (productid,productName, price, quantity) {
var self = this;
self.resultId = ko.observable(productid);
self.resultProduct = ko.observable(productName);
self.resultPrice = ko.observable(price);
self.resultQuantity = ko.observable(quantity || 1);
self.subtotal = ko.computed(function () {
return self.resultPrice() * self.resultQuantity();
});
};
$('#addProduct').click(function (line) {
var context = ko.contextFor(this);
var existing = self.find(line.resultId);
var lines = self.lines();
if (existing) {
existing.resultQuantity = existing.resultQuantity() + context.$data.Quantity();
}else{
existing = new CartLine(self.product().productid, self.product().name, self.product().price, context.$data.Quantity());
self.lines.push(existing);
}
return existing;
});
self.find = function (productid) {
return ko.utils.arrayFirst(self.lines(), function (line) {
return line.resultId === productid;
});
};
This is the full code: http://jsfiddle.net/pf9hd3Lg/2/
There are a number of errors with the code you have listed above. The below should work for the scenario you described. I have tried to comment my changes in the code below.
var CartLine = function (productid,productName, price, quantity) {
var self = this;
self.resultId = ko.observable(productid);
self.resultProduct = ko.observable(productName);
self.resultPrice = ko.observable(price);
self.resultQuantity = ko.observable(quantity || 1);
self.subtotal = ko.computed(function () {
return self.resultPrice() * self.resultQuantity();
});
};
var Cart = function() {
var self = this;
self.products = ko.observableArray([{
"productid": "1",
"name": "CAPUCINO ",
"price": 170
},
{
"productid": "2",
"name": "Sữa bò tươi",
"price": 140
}
,
{
"productid": "3",
"name": "Phô mai mặn",
"price": 170
}, {
"productid": "4",
"name": "Bơ đậu phộng ",
"price": 150
},
{
"productid": "5",
"name": "Bạc Hà",
"price": 160
},
{
"productid": "6",
"name": "Dâu Tây",
"price": 160
}
]);
self.product = ko.observable("");
self.Quantity = ko.observable(1).extend({ numeric: 0 });
self.price = ko.observable();
self.productid = ko.observable("");
self.lines = ko.observableArray();
self.grandTotal = ko.pureComputed(function () {
var total = 0;
$(self.lines()).each(function (index, line) { total += line.subtotal() })
return total;
});
$('#addProduct').click(function (line) {
var context = ko.contextFor(this);
var existing = self.find();
var lines = self.lines();
if (existing) {
//existing.resultQuantity is also an observable and should be set this way and not with the = operator
existing.resultQuantity(existing.resultQuantity() + context.$data.Quantity());
}else{
existing = new CartLine(self.product().productid, self.product().name, self.product().price, context.$data.Quantity());
self.lines.push(existing);
}
return existing;
});
self.removeProduct = function (line,event) {
self.lines.remove(line);
};
self.find = function () {
return ko.utils.arrayFirst(self.lines(), function (line) {
//resultId is an observable
//self.product().productid is what you are interested in, no need to pass it into the function
return line.resultId() === self.product().productid;
});
};
}
ko.applyBindings(new Cart());
I am trying to load a form where I can update the existing data from the database.
My Object has one nested array in inside each element in that array also have a nested array.
It looks like the following
{
"Id": 13,
"Name": "Category 1",
"DeliveryOptions":
[
{
"Id": 15,
"DeliveryCategoryId": 13,
"Name": "Option 1.-1",
"DeliveryBreakPoints":
[
{
"Id": 19,
"DeliveryOptionId": 15,
"Start": 0,
"End": 10,
"Flat": 1,
"Variable": 2,
"Delete": false
}
]
},
{
"Id": 16,
"DeliveryCategoryId": 13,
"Name": "Option1-2",
"DeliveryBreakPoints":
[
{
"Id": 20,
"DeliveryOptionId": 16,
"Start": 0,
"End": null,
"Flat": 1,
"Variable": 3,
"Delete": false
}
]
}
]
}
You can see inside the object there's an array called "DeliveryOptions" and each "DeliveryOptions" array has another array called "DeliveryBreakPoints"
I have configured knockout js model as the following
function DeliveryCategory(id, name, options) {
this.Id = id;
this.Name = name;
this.DeliveryOptions = ko.observableArray(options);
}
function DeliveryOption(id, name, breakpoint) {
bpIdCounter = 0;
this.Id = id;
this.Name = name;
this.DeliveryBreakPoints = ko.observableArray(breakpoint);
this.addDeliveryBreakPoint = function (option) {
option.DeliveryBreakPoints.push(new DeliveryBreakPoint(bpIdCounter++));
}
}
function DeliveryBreakPoint(id, start, end, flat, variable) {
var self = this;
self.Id = id;
self.Start = start;
self.End = end;
self.Flat = flat;
self.Variable = variable;
}
I am passing parameters (such as id and name ...) as this code is also used to create new object.. However I am not sure if this is preventing it to get the existing model binded.
I also created a view model which looks like this
function DeliveryCategoryViewModel(model) {
var self = this;
if (model.Id > 0) {
self.DeliveryCategory = ko.observable(model);
} else {
self.DeliveryCategory = ko.observable(new DeliveryCategory(null, "", [new DeliveryOption(null, "")]));
}
self.addDeliveryOption = function () {
self.DeliveryCategory().DeliveryOptions.push(new DeliveryOption(null, "", [new DeliveryBreakPoint(null,"0","","","","")]));
}
self.removeDeliveryOption = function (option) {
self.DeliveryCategory().DeliveryOptions.remove(option);
}
self.removeDeliveryBreakPoint = function (option, breakPoint) {
option.DeliveryBreakPoints.remove(breakPoint);
}
self.onSubmit = function () {
$.ajax({
url: "CreateDeliveryCategory",
type: "POST",
data: ko.toJSON(self),
async: true,
contentType: "application/json"
}).success(function (data) {
window.location = data;
}).error(function(error){
alert(error);
})
}
}
This code is also used when I create a new delivery category from the scratch which works fine(this is why there is a check for "model.Id > 0"). It doesn't bind the model if model.id > 0. It only displays Delivery Category name and the first Delivery Option name correctly(even there are two delivery options) and the rest is just broken.
Can anyone please pinpoint what is going on?
This is my first time using knockout. Is this the correct way to structure the ViewModel? I'm reading/writing from a JSON file that's got a fair bit of nesting.
Creating the model to just write was easy. Getting it to also read the JSON required if/else statements in the mapping objects. Which I feel is not correct.
Any input would be greatly appreciated.
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) {
for (var i=0; i < data.surveys.length; 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 is 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"
}
]
}
This is how I would do it.
JSFiddle Demo
var jsonData = {
"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"
}]
};
function Survey(name, panes, tester) {
var self = this;
self.name = ko.observable(name);
self.panes = ko.observableArray();
self.tester = ko.observable(tester);
var mappedPanes = $.map(panes, function (item, index) {
return new Pane(item);
});
self.panes(mappedPanes);
return self;
}
function Pane(pane) {
var self = this;
self.type = ko.observable(pane.type || '');
self.head = ko.observable(pane.head || '');
self.content = ko.observable(pane.content || '');
self.options = ko.observableArray();
var mappedOptions = $.map(pane.options, function (item, index) {
return new PaneOptions(item);
});
self.options(mappedOptions);
return self;
}
function PaneOptions(option) {
var self = this;
this.data = ko.observable(option.data || '');
this.target = ko.observable(option.target || '');
return self;
}
function SurveyViewModel() {
var self = this;
self.surveys = ko.observableArray([]);
/* Commented out as JSON data is included above
$.getJSON("create/fetch", function (data) {
$.each(jsonData.surveys, function (index, item) {
self.surveys.push(new Survey(item.name, item.panes, item.tester));
});
}
});
*/
$.each(jsonData.surveys, function (index, item) {
self.surveys.push(new Survey(item.name, item.panes, item.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);