Set selected on nested object knockout js - javascript

I have a complex object and I'm trying to set the
SelectedTransportation
property which I manually add in a mapping. The code properly populates the dropdownlist, but I can't figure out how to set SelectedTransportation properly. I've tried setting it during the mapping process and after mapping through a loop but all attempts have failed. Seems like this should be rather easy, but the solution eludes me.
var model = {"LoadCarriers":[
{
"Id":1,
"IsDispatched":false,
"IsPrimary":false,
"RCNotes":null,
"CarrierId":4,
"Carrier":{
"Id":4,
"Name":"West Chase",
"MCNumber":"EPZEPFEEGJAJ",
"DOTNumber":"AJSCEXFTFJ",
"InternetTruckStopCACCI":"DJOGRBQ",
"Phone":"0773283820",
"RemitToPhone":null,
"AlternatePhone":"4428290470",
"Fax":null,
"MainAddress":{
"ShortAddress":"Toledo, IN",
"Address1":"Lee St",
"Address2":"apt 131",
"City":"Toledo",
"State":"IN",
"PostalCode":"07950",
"Country":"US"
},
"RemitToAddress":{
"ShortAddress":"Fuquay Varina, MO",
"Address1":"Manchester Rd",
"Address2":"",
"City":"Fuquay Varina",
"State":"MO",
"PostalCode":"23343",
"Country":"US"
},
"EmailAddress":"jason.price14#gmail.com",
"Coverage":null,
"CanLoad":false,
"InsuranceNumber":"RIQERAIAJBMP",
"InsuranceExpirationDate":"\/Date(1442978115587)\/",
"AdditionalInsurance":null,
"ProNumber":"07643",
"URL":"http://www.west-chase.com",
"AccountId":1
},
"Dispatcher":"Bob McGill",
"DriverId":null,
"LoadDriver":{
"Id":1,
"Name":"Bobby Pittman",
"Phone":"8950121068",
"Mobile":null,
"MT":false,
"Tractor":"OQRNBP",
"Trailer":"QTZP",
"Location":"Lee St",
"TansportationSize":"958424896573544192",
"Pallets":null,
"IsDispatched":false,
"TransportationId":7,
"Transportation":{
"Name":"Flatbed or Van",
"Id":7
},
"TransportationList":[
{
"Name":"Flat",
"Id":1
},
{
"Name":"Van or Reefer",
"Id":2
},
{
"Name":"Rail",
"Id":3
},
{
"Name":"Auto",
"Id":4
},
{
"Name":"Double Drop",
"Id":5
},
{
"Name":"Flat with Tarps,",
"Id":6
},
{
"Name":"Flatbed or Van",
"Id":7
},
{
"Name":"Flatbed, Van or Reefer",
"Id":8
},
{
"Name":"Flatbed with Sides",
"Id":9
},
{
"Name":"Hopper Bottom",
"Id":10
},
{
"Name":"Hot Shot",
"Id":11
},
{
"Name":"Lowboy",
"Id":12
},
{
"Name":"Maxi",
"Id":13
},
{
"Name":"Power Only",
"Id":14
},
{
"Name":"Reefer w/ Pallet Exchange",
"Id":15
},
{
"Name":"Removable Gooseneck",
"Id":16
},
{
"Name":"Step Deck",
"Id":17
},
{
"Name":"Tanker",
"Id":18
},
{
"Name":"Curtain Van",
"Id":19
},
{
"Name":"Flatbed Hazardous",
"Id":20
},
{
"Name":"Reefer Hazardous",
"Id":21
},
{
"Name":"Van Hazardous",
"Id":22
},
{
"Name":"Vented Van",
"Id":23
},
{
"Name":"Van w/ Pallet Exchange",
"Id":24
},
{
"Name":"B-Train",
"Id":25
},
{
"Name":"Container",
"Id":26
},
{
"Name":"Double Flat",
"Id":27
},
{
"Name":"Flatbed or Stepdeck",
"Id":28
},
{
"Name":"Air",
"Id":29
},
{
"Name":"Ocean",
"Id":30
},
{
"Name":"Walking Floor",
"Id":31
},
{
"Name":"Landoll Flatbed",
"Id":32
},
{
"Name":"Conestoga",
"Id":33
},
{
"Name":"Load Out",
"Id":34
},
{
"Name":"Van Air-Ride",
"Id":35
},
{
"Name":"Container Hazardous",
"Id":36
}
],
"CarrierId":0,
"Carrier":null
},
"Carriers":null,
"LoadId":1
}
]};
var loadDriverModel = function (data) {
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.observable();
};
var loadDriverMapping = {
'LoadDriver': {
key: function (data) {
return data.Id;
},
create: function (options) {
return new loadDriverModel(options.data);
}
}
};
var carrierModel = function (data) {
ko.mapping.fromJS(data, loadDriverMapping, this);
};
var carrierMapping = {
'LoadCarriers': {
key: function (data) {
return data.Id;
},
create: function (options) {
return new carrierModel(options.data);
}
}
};
var model = ko.mapping.fromJS(model);
ko.applyBindings(model);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>
<!-- ko foreach: LoadCarriers -->
<select class="form-control" data-bind="options:LoadDriver.TransportationList, optionsText:'Name', value:$data.LoadDriver.SelectedTransportation"></select>
<!-- /ko -->

#JasonlPrice I can't test right now, but I suggest you to not use this in loadDriverModel function.
Try create a variable and return that variable.
Something like this:
var loadDriverModel = function (data) {
var viewModel = ko.mapping.fromJS(data);
viewModel.SelectedTransportation = ko.observable();
return viewModel;
};

I ended up replacing this
var loadDriverModel = function (data) {
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.observable();}
with the following.
var loadDriverModel = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
this.SelectedTransportation = ko.computed(function () {
return ko.utils.arrayFirst(self.TransportationList(), function (item) { return item.Id() === self.TransportationId() });
}, self);
};
Now it works properly. Computed Observables were the solution.

Related

Computed property in a v-loop workaround

I'm trying to make the code below work knowing that computed properties can't take parameters. Do you have any idea ? I'm exploring the use of watchers on functions but I was wondering if there was not an easier solution to do this.
var app = new Vue({
el: '#app',
data() {
return {
sessions: {
"156": {
tickets: {
"01": {
available: true,
},
"02": {
available: false,
},
}
},
},
tickets: {
"01": {
attr: "somestring",
},
"02": {
attr: "someotherstring",
},
},
},
};
},
computed: {
sessionTickets(session) {
let _this = this;
let sessionTickets = {};
$.each(_this.session.tickets, function(ticketId, sessionTicket) {
if(sessionTicket.available) {
sessionTickets[ticketId] = _this.tickets[ticketId];
}
});
return sessionTickets;
},
},
});
<div v-for="session in sessions">
<div v-for="sessionTicket in sessionTickets(session)">
{{ sessionTicket.attr }}
</div>
</div>
Thanks to "WallOp" for making me realize that my computed property is in a sessions loop and so it can normally become a class method and be refreshed on sessions refresh !
I think you can use computed property. Just filter tickets of sessions. Like this:
var app = new Vue({
el: '#app',
data() {
return {
sessions: {
"156": {
tickets: {
"01": {
available: true,
},
"02": {
available: false,
},
}
},
},
tickets: {
"01": {
attr: "somestring",
},
"02": {
attr: "someotherstring",
},
},
},
};
computed: {
filteredSessions() {
return this.sessions.map( session => {
let tickets = {};
for(key in session.tickets) {
if(session.tickets[key].available && this.tickets.hasOwnProperty(key)) {
tickets[key] = this.tickets[key];
}
}
session.tickets = tickets;
return session;
});
},
},
});
<div v-for="session in filteredSessions">
<div v-for="ticket in session.tickets">
{{ ticket.attr }}
</div>
</div>

Cascade Dropdown JSON

Yes, this has been posted many times. But I am unable to locate the assistance I need in the other posts. I have a JSON which I am using to populate cascading dropdowns. The initial population of the first dropdown works great, but I am unable to have the other two populate. I believe it is due to the nested arrays in JSON of which I have tried looping, nested looping etc......
Here is my JSON:
"DATA": [
{
"productcodelist": [
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
}
],
"productcodevalue": 10055440000148
},
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
}
],
"productcodevalue": 10071179018124
},
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
},
{
"tablenamevalue": "ProcessGradingFry"
},
{
"tablenamevalue": "UODrying"
},
{
"tablenamevalue": "UOFreezing"
}
],
"productcodevalue": 10071179036432
},
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
},
{
"tablenamevalue": "ProcessGradingFry"
},
{
"tablenamevalue": "UODrying"
},
{
"tablenamevalue": "UOFreezing"
}
],
"productcodevalue": 10071179037545
},
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
},
{
"tablenamevalue": "ProcessGradingFry"
},
{
"tablenamevalue": "UODrying"
},
{
"tablenamevalue": "UOFreezing"
}
],
"productcodevalue": 10071179037613
},
{
"tablenamelist": [
{
"tablenamevalue": "FryLineProcessGrading"
},
{
"tablenamevalue": "ProcessGradingFry"
},
{
"tablenamevalue": "UODrying"
},
{
"tablenamevalue": "UOFreezing"
}
],
"productcodevalue": 10071179462033
}
],
"linevalue": 1
},
{
"productcodelist": [
{
"tablenamelist": [
{
"tablenamevalue": "HalverSizeCounts"
}
],
"productcodevalue": 10071179036449
}
],
"linevalue": 2
},
{
"productcodelist": [
{
"tablenamelist": [
{
"tablenamevalue": "MetalDetectorCheckSheet"
}
],
"productcodevalue": 10071179036432
}
],
"linevalue": 10
}
]
}
Here is my JavaScript code:
$(document).ready(function(){
var specData = [];
var lineCategory = $('#line').val();
var productcodeCategory = $('#productcode').val();
$.ajax(
{
type: "get",
url: "index.cfm?controller=ProcessSpecs&Action=getSpecData",
dataType: "json",
success: function(objResponse) {
if (objResponse.SUCCESS == true) {
specData = objResponse.DATA;
$('#line')
.append('<option>Select Lines</option>')
$.each(specData, function(k, v) {
$('#line')
.append($('<option>', {value : v.linevalue})
.text(v.linevalue))
});
$('#line').val(linevalue).trigger('change');
} else {
}
},
error: function(objRequest, strError) {
}
});
$('#line').change(function() {
var val = $(this).val();
var specSelected = jQuery.grep(specData, function(element, index) {
if (element.linevalue == val) {
return element.productcodelist;
}
});
$('#productcode')
.find('option')
.remove()
.end();
$.each(specData.productcodelist, function(k, v) {
$('#productcode')
.append($('<option>', {value: v.productcodevalue})
.text(v.productcodevalue));
});
});
});
The #line change function will start but I am unable to get the productcodevalue to be created and populated in the productcode dropdown. The following code does work to get the JSON data that is associated with a specific line.
var specSelected = jQuery.grep(specData, function(element, index) {
if (element.linevalue == val) {
return element.productcodelist;
}
});
Verified by adding:
alert(JSON.stringify(specSelected));
But after that anything I have tried or plagiarized has not worked in populating the productcodevalue into the #productcode select box.
<form name="getSpecData">
<select name="line" id="line">
</select>
<select name="productcode" id="productcode">
</select>
<select name="tablename" id="tablename">
</select>
<input type="Submit" value="Get Specs" />
</form>
Any advice, assistance, and or guidance is appreciated.
Update: I have figured out how to populate the #productcode select. Not elegant, but workable.
$('#line').change(function() {
var val = $(this).val();
var specSelected = jQuery.grep(specData, function(element, index) {
if (element.linevalue == val) {
return element.productcodelist;
}
});
$('#productcode')
.find('option')
.remove()
.end();
$('#productcode')
.append('<option>Select Product Code</option>')
$('#tablename')
.append('<option>Select Product Code First</option>')
for (productcodelist in specSelected) {
for (tablenamelist in specSelected[productcodelist]) {
$.each(specSelected[productcodelist][tablenamelist], function(k, v) {
$('#productcode')
.append($('<option>', {value: v.productcodevalue})
.text(v.productcodevalue));
});
}
}
});
Still seeking advice on the third dropdown for tablename since it is a nested array that will need to equal the line and productcode dropdowns.
Not elegant, but figured it out. Since it works I will close this. If anyone sees a way I can improve my code, by all means post your recommendations here.
$('#productcode').change(function() {
var lineval = $('#line').val();
var productcodeval = $("#productcode").val();
var specSelected = jQuery.grep(specData, function(element, index) {
if (element.linevalue == lineval) {
return element.productcodelist;
}
});
$('#tablename')
.find('option')
.remove()
.end();
$('#tablename')
.append('<option>Select Product Code</option>')
for (productcodelist in specSelected) {
for (tablenamelist in specSelected[productcodelist]) {
for (productcodevalue in specSelected[productcodelist][tablenamelist]) {
if(specSelected[productcodelist][tablenamelist][productcodevalue].productcodevalue == productcodeval) {
for (tablenamevalue in specSelected[productcodelist][tablenamelist][productcodevalue]) {
$.each(specSelected[productcodelist][tablenamelist][productcodevalue][tablenamevalue], function(k, v) {
$('#tablename')
.append($('<option>', {value: v.tablenamevalue})
.text(v.tablenamevalue));
});
}
}
}
}
}
});

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

I need some help with this error:
Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse ()
at Object.success (dashboard.js:22)
at fire (jquery-3.3.1.js:3268)
at Object.fireWith [as resolveWith] (jquery-3.3.1.js:3398)
at done (jquery-3.3.1.js:9305)
at XMLHttpRequest. (jquery-3.3.1.js:9548)
I try to transform a string to a json object using JSON.parse() that cause that error.
I am using oracleJet and this is my code:
function DashboardViewModel() {
var self = this;
self.lineTypeValue = ko.observable('curved');
var scatterSeries = [];
$.getJSON( "http://localhost:8080/points", function (data) {
console.info(data);
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';
console.info(ch);
console.info(JSON.parse(scatterSeries));
scatterSeries.push(JSON.parse(ch));
});
/* chart data */
this.scatterSeriesValue = ko.observableArray(scatterSeries);
self.lineTypeOptions = [
{id: 'straight', label: 'straight'},
{id: 'curved', label: 'curved'},
{id: 'stepped', label: 'stepped'},
{id: 'segmented', label: 'segmented'},
{id: 'none', label: 'none'}
];
}
The Json that I get from "http://localhost:8080/points" look like this:
{ "results":[
[
{
"b":"0.110547334",
"cost":"0.000000",
"w":"1.998889"
}
],
[
{
"x":0,
"y":0
},
{
"x":1,
"y":2
},
{
"x":2,
"y":4
},
{
"x":3,
"y":6
},
{
"x":4,
"y":8
},
{
"x":5,
"y":10
},
{
"x":6,
"y":12
},
{
"x":7,
"y":14
},
{
"x":8,
"y":16
},
{
"x":9,
"y":18
},
{
"x":10,
"y":20
},
{
"x":11,
"y":22
},
{
"x":12,
"y":24
},
{
"x":13,
"y":26
},
{
"x":14,
"y":28
},
{
"x":15,
"y":30
},
{
"x":16,
"y":32
},
{
"x":17,
"y":34
},
{
"x":18,
"y":36
},
{
"x":19,
"y":38
},
{
"x":20,
"y":40
},
{
"x":21,
"y":42
},
{
"x":22,
"y":44
},
{
"x":23,
"y":46
},
{
"x":24,
"y":48
},
{
"x":25,
"y":50
},
{
"x":26,
"y":52
},
{
"x":27,
"y":54
},
{
"x":28,
"y":56
},
{
"x":29,
"y":58
},
{
"x":30,
"y":60
},
{
"x":31,
"y":62
},
{
"x":32,
"y":64
},
{
"x":33,
"y":66
},
{
"x":34,
"y":68
},
{
"x":35,
"y":70
},
{
"x":36,
"y":72
},
{
"x":37,
"y":74
},
{
"x":38,
"y":76
},
{
"x":39,
"y":78
},
{
"x":40,
"y":80
},
{
"x":41,
"y":82
},
{
"x":42,
"y":84
},
{
"x":43,
"y":86
},
{
"x":44,
"y":88
},
{
"x":45,
"y":90
},
{
"x":46,
"y":92
},
{
"x":47,
"y":94
},
{
"x":48,
"y":96
},
{
"x":49,
"y":98
},
{
"x":50,
"y":100
},
{
"x":51,
"y":102
},
{
"x":52,
"y":104
},
{
"x":53,
"y":106
},
{
"x":54,
"y":108
},
{
"x":55,
"y":110
},
{
"x":56,
"y":112
},
{
"x":57,
"y":114
},
{
"x":58,
"y":116
},
{
"x":59,
"y":118
},
{
"x":60,
"y":120
},
{
"x":61,
"y":122
},
{
"x":62,
"y":124
},
{
"x":63,
"y":126
},
{
"x":64,
"y":128
},
{
"x":65,
"y":130
},
{
"x":66,
"y":132
},
{
"x":67,
"y":134
},
{
"x":68,
"y":136
},
{
"x":69,
"y":138
},
{
"x":70,
"y":140
},
{
"x":71,
"y":142
},
{
"x":72,
"y":144
},
{
"x":73,
"y":146
},
{
"x":74,
"y":148
},
{
"x":75,
"y":150
},
{
"x":76,
"y":152
},
{
"x":77,
"y":154
},
{
"x":78,
"y":156
},
{
"x":79,
"y":158
},
{
"x":80,
"y":160
},
{
"x":81,
"y":162
},
{
"x":82,
"y":164
},
{
"x":83,
"y":166
},
{
"x":84,
"y":168
},
{
"x":85,
"y":170
},
{
"x":86,
"y":172
},
{
"x":87,
"y":174
},
{
"x":88,
"y":176
},
{
"x":89,
"y":178
},
{
"x":90,
"y":180
},
{
"x":91,
"y":182
},
{
"x":92,
"y":184
},
{
"x":93,
"y":186
},
{
"x":94,
"y":188
},
{
"x":95,
"y":190
},
{
"x":96,
"y":192
},
{
"x":97,
"y":194
},
{
"x":98,
"y":196
},
{
"x":99,
"y":198
}
]]}
and what I want the variable scatterSeries to hold is a table like this one:
[ {
name:"graphe1",
items:[
{
x:8,
y:2
},
{
x:15,
y:15
},
{
x:25,
y:26
},
{
x:33,
y:22
},
{
x:36,
y:40
}
]},]
what I get in the console about the string ch is this:
{"name":"graphe1","items":[{"x":0,"y":0},{"x":1,"y":2},{"x":2,"y":4},{"x":3,"y":6},{"x":4,"y":8},{"x":5,"y":10},{"x":6,"y":12},{"x":7,"y":14},{"x":8,"y":16},{"x":9,"y":18},{"x":10,"y":20},{"x":11,"y":22},{"x":12,"y":24},{"x":13,"y":26},{"x":14,"y":28},{"x":15,"y":30},{"x":16,"y":32},{"x":17,"y":34},{"x":18,"y":36},{"x":19,"y":38},{"x":20,"y":40},{"x":21,"y":42},{"x":22,"y":44},{"x":23,"y":46},{"x":24,"y":48},{"x":25,"y":50},{"x":26,"y":52},{"x":27,"y":54},{"x":28,"y":56},{"x":29,"y":58},{"x":30,"y":60},{"x":31,"y":62},{"x":32,"y":64},{"x":33,"y":66},{"x":34,"y":68},{"x":35,"y":70},{"x":36,"y":72},{"x":37,"y":74},{"x":38,"y":76},{"x":39,"y":78},{"x":40,"y":80},{"x":41,"y":82},{"x":42,"y":84},{"x":43,"y":86},{"x":44,"y":88},{"x":45,"y":90},{"x":46,"y":92},{"x":47,"y":94},{"x":48,"y":96},{"x":49,"y":98},{"x":50,"y":100},{"x":51,"y":102},{"x":52,"y":104},{"x":53,"y":106},{"x":54,"y":108},{"x":55,"y":110},{"x":56,"y":112},{"x":57,"y":114},{"x":58,"y":116},{"x":59,"y":118},{"x":60,"y":120},{"x":61,"y":122},{"x":62,"y":124},{"x":63,"y":126},{"x":64,"y":128},{"x":65,"y":130},{"x":66,"y":132},{"x":67,"y":134},{"x":68,"y":136},{"x":69,"y":138},{"x":70,"y":140},{"x":71,"y":142},{"x":72,"y":144},{"x":73,"y":146},{"x":74,"y":148},{"x":75,"y":150},{"x":76,"y":152},{"x":77,"y":154},{"x":78,"y":156},{"x":79,"y":158},{"x":80,"y":160},{"x":81,"y":162},{"x":82,"y":164},{"x":83,"y":166},{"x":84,"y":168},{"x":85,"y":170},{"x":86,"y":172},{"x":87,"y":174},{"x":88,"y":176},{"x":89,"y":178},{"x":90,"y":180},{"x":91,"y":182},{"x":92,"y":184},{"x":93,"y":186},{"x":94,"y":188},{"x":95,"y":190},{"x":96,"y":192},{"x":97,"y":194},{"x":98,"y":196},{"x":99,"y":198}]}
Any help please?!! :( :(
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries is not JSON. Do not try to parse it as JSON.
data is not JSON either (getJSON will parse it as JSON automatically).
ch is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.
I was trying to debug this same error (I was writing code in TypeScript), but no matter what I did, the error didn't go away, it was really persistent.
I tried to look into the solution in many blogs and also this SO thread. I tried everything and nothing worked out.
Finally, I saw that I created the required file named products.json in which I gave a single extra newline (meaning, previously the file had 1 empty line, now it had 2 empty lines) and was following good GitHub practices as mentioned here.
Because of that single extra newline in my products.json file, I wasted 2 hours fixing a bug that didn't exist in the first place.
Finally when I deleted the entire products.json file and re-ran the entire thing, I didn't get any runtime errors and everything was running without any problems.
What I learned by going through all this?
It's that experience is the teacher of all things.
Remove this line from your code:
console.info(JSON.parse(scatterSeries));
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[
[
{
"b":"0.110547334",
"cost":"0.000000",
"w":"1.998889"
}
],
[
{
"x":0,
"y":0
},
{
"x":1,
"y":2
},
{
"x":2,
"y":4
},
{
"x":3,
"y":6
},
{
"x":4,
"y":8
},
{
"x":5,
"y":10
},
{
"x":6,
"y":12
},
{
"x":7,
"y":14
},
{
"x":8,
"y":16
},
{
"x":9,
"y":18
},
{
"x":10,
"y":20
},
{
"x":11,
"y":22
},
{
"x":12,
"y":24
},
{
"x":13,
"y":26
},
{
"x":14,
"y":28
},
{
"x":15,
"y":30
},
{
"x":16,
"y":32
},
{
"x":17,
"y":34
},
{
"x":18,
"y":36
},
{
"x":19,
"y":38
},
{
"x":20,
"y":40
},
{
"x":21,
"y":42
},
{
"x":22,
"y":44
},
{
"x":23,
"y":46
},
{
"x":24,
"y":48
},
{
"x":25,
"y":50
},
{
"x":26,
"y":52
},
{
"x":27,
"y":54
},
{
"x":28,
"y":56
},
{
"x":29,
"y":58
},
{
"x":30,
"y":60
},
{
"x":31,
"y":62
},
{
"x":32,
"y":64
},
{
"x":33,
"y":66
},
{
"x":34,
"y":68
},
{
"x":35,
"y":70
},
{
"x":36,
"y":72
},
{
"x":37,
"y":74
},
{
"x":38,
"y":76
},
{
"x":39,
"y":78
},
{
"x":40,
"y":80
},
{
"x":41,
"y":82
},
{
"x":42,
"y":84
},
{
"x":43,
"y":86
},
{
"x":44,
"y":88
},
{
"x":45,
"y":90
},
{
"x":46,
"y":92
},
{
"x":47,
"y":94
},
{
"x":48,
"y":96
},
{
"x":49,
"y":98
},
{
"x":50,
"y":100
},
{
"x":51,
"y":102
},
{
"x":52,
"y":104
},
{
"x":53,
"y":106
},
{
"x":54,
"y":108
},
{
"x":55,
"y":110
},
{
"x":56,
"y":112
},
{
"x":57,
"y":114
},
{
"x":58,
"y":116
},
{
"x":59,
"y":118
},
{
"x":60,
"y":120
},
{
"x":61,
"y":122
},
{
"x":62,
"y":124
},
{
"x":63,
"y":126
},
{
"x":64,
"y":128
},
{
"x":65,
"y":130
},
{
"x":66,
"y":132
},
{
"x":67,
"y":134
},
{
"x":68,
"y":136
},
{
"x":69,
"y":138
},
{
"x":70,
"y":140
},
{
"x":71,
"y":142
},
{
"x":72,
"y":144
},
{
"x":73,
"y":146
},
{
"x":74,
"y":148
},
{
"x":75,
"y":150
},
{
"x":76,
"y":152
},
{
"x":77,
"y":154
},
{
"x":78,
"y":156
},
{
"x":79,
"y":158
},
{
"x":80,
"y":160
},
{
"x":81,
"y":162
},
{
"x":82,
"y":164
},
{
"x":83,
"y":166
},
{
"x":84,
"y":168
},
{
"x":85,
"y":170
},
{
"x":86,
"y":172
},
{
"x":87,
"y":174
},
{
"x":88,
"y":176
},
{
"x":89,
"y":178
},
{
"x":90,
"y":180
},
{
"x":91,
"y":182
},
{
"x":92,
"y":184
},
{
"x":93,
"y":186
},
{
"x":94,
"y":188
},
{
"x":95,
"y":190
},
{
"x":96,
"y":192
},
{
"x":97,
"y":194
},
{
"x":98,
"y":196
},
{
"x":99,
"y":198
}
]]};
var scatterSeries = [];
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';
console.info(ch);
scatterSeries.push(JSON.parse(ch));
console.info(scatterSeries);
code sample - https://codepen.io/nagasai/pen/GGzZVB
You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.
Encountered this error in the following function when I tried to pull 'nothing' from LS
Quick fix for posterity
const getUserFromLocalStorage = () => {
try {
return JSON.parse(localStorage.getItem('user') || '');
} catch (error) {
return null;
}
};
In my case, using .NET 6, the problem was that the controller was declared as void and did not return any value.
Simply changing the method declaration to int and adding return 0; solved this issue for me.
[HttpPost]
public int MyMethod(string text)
{
_logger.Log(text);
return 0;
}
This is because of the data that you are trying to parse is not in a parsable format .
so i suggest to check the data is parsable or not before define the parse.
const IsParsable = (data) => {
try {
JSON.parse(data);
} catch (e) {
return false;
}
return true;
}
var Obj= JSON.stringify({
"name": "graphe1",
"items": data.results[1]
})
return IsParsable (Obj) ? JSON.parse(Obj) : false

Dialogue.Directive Not Working When emiting the handler ?

After A dialogue is completed and its confirmationStatus is changed to confirmed than i emit another dialogue directive ./ intent but its directive dosent work and it directly jumps to emit and ends
code :-
const handlers = {
'LaunchRequest': function () {
this.response.speak(welcomeOutput).listen(welcomeReprompt);
var userID = this.event.session.user.userID;
console.log(userID);
this.emit(':responseReady');
},
'createOrder': function () {
var filledSlots = delegateSlotCollection.call(this);
this.emit(':tell','Create Order Ended');
},
'addOrder': function () {
var filledSlots = delegateSlotCollectionSecond.call(this);
},
'AMAZON.HelpIntent': function () {
speechOutput = "";
reprompt = "";
this.response.speak(speechOutput).listen(reprompt);
this.emit(':responseReady');
},
'AMAZON.YesIntent': function () {
this.emit("Yes Triggered");
},
'AMAZON.NoIntent': function () {
this.emit("NO Triggered");
},
'AMAZON.CancelIntent': function () {
speechOutput = "Okay Your Request is Cancelled";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'AMAZON.StopIntent': function () {
speechOutput = "";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'SessionEndedRequest': function () {
var speechOutput = "";
this.response.speak(speechOutput);
this.emit(':responseReady');
},
'AMAZON.FallbackIntent': function () {
console.log('AMAZON FALL BACKINTENT');
},
'Unhandled': function () {
console.log("Unhandled");
},
};
exports.handler = (event, context) => {
var alexa = Alexa.handler(event, context);
alexa.appId = APP_ID;
// To enable string internationalization (i18n) features, set a resources object.
//alexa.resources = languageStrings;
alexa.registerHandlers(handlers);
alexa.execute();
};
// END of Intent Handlers {} ========================================================================================
// 3. Helper Function =================================================================================================
function delegateSlotCollection() {
console.log("in delegateSlotCollection");
console.log("current dialogState: " + this.event.request.dialogState);
if (this.event.request.dialogState === "STARTED") {
var updatedIntent = this.event.request.intent;
this.emit(":delegate", updatedIntent);
} else if (this.event.request.dialogState !== "COMPLETED") {
console.log("in not completed");
this.emit(":delegate")
} else {
if (this.event.request.intent.confirmationStatus === 'CONFIRMED'){
this.emit('addOrder');
}
return this.event.request.intent;
}
}
function delegateSlotCollectionSecond() {
console.log("in delegateSlotCollection");
console.log("current dialogState: " + this.event.request.dialogState);
if (this.event.request.dialogState === "STARTED") {
var updatedIntent = this.event.request.intent;
this.emit(":delegate", updatedIntent);
} else if (this.event.request.dialogState !== "COMPLETED") {
console.log("in not completed");
this.emit(":delegate")
} else {
if (this.event.request.intent.confirmationStatus === 'CONFIRMED'){
Console.log("Vegeta");
console.log(this.event.request.intent.confirmationStatus);
}
return this.event.request.intent;
}
}
This Is the code that i am using so when first createOrder Dialogue is completed it ask for confirmation and when i say yes than add order is emited but its dialogue directive didnt work it directly emits the statement so how to solve tghis problem ?
'createOrder': function () {
this.emit(':ask','tell me item name');
},
'productIntent': function(){
this.event.request.intent.slots.product.value //have an intent and slot for product
this.attributes['anyName'] = "product"; put product in session
this.emit(':ask','tell me quantity');
}
'quantityIntent': function(){
this.event.request.intent.slots.quantity.value //have an intent and slot for quality
this.attributes['anyName'] = "quantity"; put quantity in session
this.emit(':ask','do you want to add more item');
}
'Amazon.yesIntent': function () {
this.emit("createOrder"); //repeat
},
//handle no intent by retrieving all data and making your order
let retriveddata = this.attributes['anyName'];
You get the idea.
This way you won't lose the data between intents unless the session ends.
{
"interactionModel": {
"languageModel": {
"invocationName": "hello order",
"intents": [
{
"name": "AMAZON.FallbackIntent",
"samples": []
},
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "CreateOrder",
"slots": [],
"samples": []
},
{
"name": "ProductIntent",
"slots": [
{
"name": "productType",
"type": "products"
}
],
"samples": [
"{productType}"
]
},
{
"name": "QuanityIntent",
"slots": [
{
"name": "quantiyValue",
"type": "AMAZON.NUMBER"
}
],
"samples": [
"{quantiyValue}"
]
},
{
"name": "AMAZON.YesIntent",
"samples": []
},
{
"name": "AMAZON.NoIntent",
"samples": []
}
],
"types": [
{
"name": "products",
"values": [
{
"name": {
"value": "burger"
}
},
{
"name": {
"value": "pizza"
}
}
]
}
]
}
}
}

knockout mapping from JS with extra proeprties

I have this jSON structure.
{
"customer": {
"idcustomer": 2,
"name": "test_2",
"vat": "test_vat_2",
"obs": "obs_2",
"deleted": 0
},
"addresses": [
{
"idaddress": 9,
"street": "street_2_9",
"number": "number_2_9",
"country": "country_2_9",
"default": true,
"label": "labe_2_9",
"deleted": 0
},
{
"idaddress": 10,
"street": "1",
"number": "number_2_9",
"country": "country_2_10",
"default": false,
"label": "label_2_10",
"deleted": 0
}
],
"contacts": []
}
With knockout mapping plugin I am able to generate a knockout observable object. However, when trying to add extra properties to the object using the mapping parameter I find some issues. The goal is to add "SelectedAddress" to the main object and in each address a "defaultLabel" observabale.
Currently i have this mapping structure to add the property to the address children:
var mapping = {
'addresses': {
create: function (options) {
return (new (function () {
this.defaultLabel= ko.computed(function () {
return (this.default() == 0) ? "" : this.label();
}, this);
ko.mapping.fromJS(options.data, {}, this);
})());
}
},
}
and this to add the "SelectedAddress" to the main JSON:
create: function (options) {
return new function () {
var model = ko.mapping.fromJS(options.data, {}, this);
// Direccion
model.direccionSeleccionada = ko.observable();
model.getDireccion = ko.computed({
read: function() {
if (model.direccionSeleccionada() != null) {
return model.direccionSeleccionada();
} else {
return [{
idaddress: -1,
street : '',
number: '',
country: '',
default: '',
label: '',
deleted: '',
}];
}
},
write: function(value) {
self.direccionSeleccionada(value);
},
owner: self
});
}
}
I can not find a way to have them both
Ideas?
Thank you
I figured it out. Just for someone; Just as simple as when generatint he mapping of "addresses", add inside another mapping for it.
var mapping = {
create: function (options) {
return new function () {
var model = ko.mapping.fromJS(options.data, {
'adresses': {
create: function (options) {
return (new(function () {
this.labelDefault= ko.computed(function () {
return (this.default() == 0) ? "" : this.label();
}, this);
ko.mapping.fromJS(options.data, {}, this);
})( /* call the ctor here */ ));
}
},
}, this);
model.direccionSeleccionada = ko.observable();
model.getDireccion = ko.computed({
read: function () {
if (model.selectedAddress() != null) {
return model.selectedAddress();
} else {
return [{
idaddress: -1,
street: '',
number: '',
country: '',
default: '',
label: '',
deleted: ''
}];
}
},
write: function (value) {
self.selectedAddress(value);
},
owner: self
});
}
}
}
Thank you!

Categories