check for an existing product - javascript

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());

Related

CSV data processed in canvas

I want to read some data from a CSV file and create multiple canvases that contains the data from my CSV. I want each line of the CSV to have it's own canvas.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title>BaGr (Badge Generator)</title>
</head>
<body>
<h3>Create</h3>
<div id="output">
<script>
const output = document.getElementById("output");
let objects = [];
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function (){
if(this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
//parsing objects, so reusable
objects = generateObjects(this.responseText);
//once objects are parsed generate view
generateView();
}
}
xhttp.open("GET", "test.txt", true);
xhttp.send();
}
generateObjects = (responseText) => {
const lines = responseText.split("\n");
return lines.map(lineRaw=>{
const line = lineRaw.split(',');
if(line.length !== 4){
console.warn("Line error.");
return undefined;
}
return {name: line[0], surname: line[1], sex: line[2], role: line[3]};
});
}
generateView = () => {
output.innerHTML = objects.map(object=>generateCanvas(object).outerHTML).join("");
}
generateCanvas = (line) => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
let pos = 230;
for(let key in line){
if(line.hasOwnProperty(key)){
context.fillText(`${key.toUpperCase()}: `, 30, pos);
context.fillText(line[key], 150, pos);
pos += 20;
}
}
return canvas;
}
window.onload = init;
</script>
</div>
</body>
</html>
Still not working properly. When i click on inspect i see that the code has the canvases generated but they don't appear on my page.
Here is a working version of what you're looking for. If you have any questions let me know.
const output = document.getElementById("output");
let objects = [];
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//parsing objects, so reusable
objects = generateObjects(this.responseText);
//once objects are parsed generate view
generateView();
}
}
xhttp.open("GET", "test.txt", true);
xhttp.send();
}
generateObjects = (responseText) => {
const lines = responseText.split("\n");
return lines.map(lineRaw => {
const line = lineRaw.split(',');
if (line.length !== 4) {
console.warn("Line error.");
return undefined;
}
return {
name: line[0],
surname: line[1],
sex: line[2],
role: line[3]
};
});
}
generateView = () => {
objects.forEach(object => generateCanvas(object))
}
generateCanvas = (line) => {
const canvas = document.createElement("canvas");
output.appendChild(canvas);
const context = canvas.getContext("2d");
let pos = 50;
for (let key in line) {
if (line.hasOwnProperty(key)) {
context.fillText(`${key.toUpperCase()}:`, 30, pos);
context.fillText(line[key], 150, pos);
pos += 20;
}
}
}
Working example with provided data
const output = document.getElementById("output");
let objects = [{
"name": "Popescu",
"surname": "Bogdan",
"sex": "masculin",
"role": "student\r"
}, {
"name": "Prelipcean",
"surname": "Radu",
"sex": "masculin",
"role": "avocat\r"
}, {
"name": "Antonie",
"surname": "Ioana",
"sex": "feminin",
"role": "profesor\r"
}, {
"name": "Arhire",
"surname": "Raluca",
"sex": "feminin",
"role": "asistenta\r"
}, {
"name": "Panaite",
"surname": "Alexandru",
"sex": "masculin",
"role": "contabil\r"
}, {
"name": "Bodnar",
"surname": "Ioana",
"sex": "feminin",
"role": "vizitator"
}];
generateView = () => {
objects.forEach(object => generateCanvas(object))
}
generateCanvas = (line) => {
const canvas = document.createElement("canvas");
output.appendChild(canvas);
const context = canvas.getContext("2d");
let pos = 50;
for (let key in line) {
if (line.hasOwnProperty(key)) {
context.fillText(`${key.toUpperCase()}:`, 30, pos);
context.fillText(line[key], 150, pos);
pos += 20;
}
}
}
generateView();
<div id="output"></div>

An array of prices that represents 3 different prices for the same product

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;
};

Expected an identifier and instead saw '<'

I get this error at the very beginning. Not sure how to fix. I also get the expected an assignment or function call and instead saw an expression. Not to mention Expected an identifier and instead saw "var"
<script>
var interactiveSearch = {};
(function() {
interactiveSearch.common = {
init: function() {
interactiveSearch.common.setupDataTableDefaults();
$.ajaxSetup({
cache: false
});
},
setupDataTableDefaults: function() {
$.extend($.fn.dataTable.defaults, {
"sDom": "<'table-header-controls'<'row'<l><f>>r><i>t<'table-footer-controls'<'row'<'span12'p><'span12'i>>>",
"sPaginationType": "bootstrap",
"bJQueryUI": false,
"bProcessing": false,
"bServerSide": true,
"fnServerData": interactiveSearch.common.getTableData
});
},
getTableData: function(sSource, aoData, fnCallback) {
var data = new Array();
var columnCount = _.find(aoData, function(o) {
return o.name == 'iColumns';
}).value;
var echo = _.find(aoData, function(o) {
return o.name == 'sEcho';
}).value;
var skip = _.find(aoData, function(o) {
return o.name == 'iDisplayStart';
}).value;
var take = _.find(aoData, function(o) {
return o.name == 'iDisplayLength';
}).value;
var search = _.find(aoData, function(o) {
return o.name == 'sSearch';
}).value;
var sortCols = _.filter(aoData, function(o) {
return o.name.indexOf('iSortCol_') == 0;
});
var sortDirs = _.filter(aoData, function(o) {
return o.name.indexOf('sSortDir_') == 0;
});
var searches = _.filter(aoData, function(o) {
return o.name.indexOf('sSearch_') == 0;
});
data.push({
"name": "TableEcho",
"value": echo
});
data.push({
"name": "Skip",
"value": skip
});
data.push({
"name": "Take",
"value": take
});
data.push({
"name": "AllSearch",
"value": search
});
var actual = 0;
_.each(sortCols, function(columnSort, sortIndex) {
var columnIndex = columnSort.value;
var columnSearch = searches[columnIndex].value;
var sortDir = sortDirs[sortIndex].value;
data.push({
"name": "Columns[" + actual + "].ColumnIndex",
"value": columnIndex
});
data.push({
"name": "Columns[" + actual + "].SortDirection",
"value": sortDir
});
if (columnSearch != '') {
data.push({
"name": "Columns[" + actual + "].SearchTerm",
"value": columnSearch
});
}
actual++;
});
for (var i = 0; i < columnCount; i++) {
var searchTerm = searches[i].value;
if (searchTerm == '') {
continue;
}
data.push({
"name": "Columns[" + actual + "].ColumnIndex",
"value": i
});
data.push({
"name": "Columns[" + actual + "].SearchTerm",
"value": searchTerm
});
actual++;
}
$.post(sSource, data)
.success(fnCallback);
}
};
})();
$(function() {
interactiveSearch.common.init();
});
(function() {
var product = interactiveSearch.product = {};
product.init = function() {
product.initDataTable();
product.bindEvents();
};
function convertFullRowToDataObject(fullRow) {
return {
Id: fullRow[0],
ProductName: fullRow[1],
Synonym: fullRow[2],
Acronym: fullRow[3],
CasNo: fullRow[4],
EinecsNo: fullRow[5],
Formula: fullRow[6],
MolecularWeight: fullRow[7],
Status: fullRow[8],
MeltingPoint: fullRow[9],
BoilingPoint: fullRow[10],
HasDoc: fullRow[11] !== '',
RelatedDocPath: product.baseUrl + fullRow[11],
HasDImage: fullRow[12] !== '',
ImagePath: product.baseUrl + fullRow[12]
};
}
product.initDataTable = function() {
product.productTable = $("#product-table").dataTable({
aaSorting: [
[1, "asc"]
],
iDisplayLength: 15,
bServerSide: true,
bDestroy: true,
sAjaxSource: interactiveSearch.product.listUrl,
fnRowCallback: function(nRow, aData) {
$(nRow).data('rowInfo', convertFullRowToDataObject(aData));
},
aoColumns: [{
sType: "string",
sClass: "dtAlignLeft",
mData: 1
}]
});
};
product.bindEvents = function() {
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\[([\s\S]+?)\]\}/g
};
var templateText = $('#productDetailTemplate').html(),
compiledTemplate = _.template(templateText);
$(document).on('click', '#product-table tr', function(e) {
var el = $(this);
var rowData = el.data('rowInfo');
var html = compiledTemplate(rowData);
$('#productDetailContainer').empty().html(html);
$('#product-table tr').removeClass('active');
el.addClass('active');
});
$('#searchClone').on('keyup', function(e) {
var el = $(this);
var mimicEl = $('#product-table_filter input');
mimicEl.val(el.val()).trigger('keyup');
})
$('.btn-reset-filter').on('click', function() {
$('#searchClone').val('').trigger('keyup');
});
};
})();
$(document).ready(function() {
interactiveSearch.product.listUrl = '/pa/Product/ListItems';
interactiveSearch.product.baseUrl = '/pa/';
interactiveSearch.product.init();
});
</script>
In .js files you don't have to put <script>, you can just write your code.
<script> is for HTML files when you have to insert a script in the middle of the page.
So you have to delete <script> and </script> in your file.

Parsing JSON array in Javascript

I have this JSON:
var person = {"id": "1", "name": "Michel"}
How would I return "1" when "Michel" is selected.
I have tried:
for (value in person) {
if (person.hasOwnProperty(value)) {
console.log(value+ " = " + person[value]);
}
}
You mean like this?
var person = [{"id": "1", "name": "Michel"}];
for(index=0;index<person.length;index++) {
if(person[index].name == 'Michel') {
console.log(person[index].id);
}
}
Another Way
var person = [{"id": "1", "name": "Michel"}];
var string = 'Michel';
function searchArray(str) {
var id = '';
for(index=0; index<person.length; index++) {
if(person[index].name == str) {
id = person[index].id;
}
}
return id;
}
var result_id = searchArray(string);

reading data into knockout Model

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);

Categories