Dialogue.Directive Not Working When emiting the handler ? - javascript

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"
}
}
]
}
]
}
}
}

Related

How to get parent key from child in Object

Given an Object, I want to get the parent key starting from the child. Since I only care about the key I'm iterating from enntries, but it always returns undefined.
var book = {
"chapter1": {
"paragraph1": {
"text": "..."
},
"paragraph2": {
"text": "..."
}
},
"chapter2": {
"paragraph3": {
"text": "..."
},
"paragraph4": {
"text": "..."
}
},
"chapter3": {
"paragraph5": {
"text": "..."
},
"paragraph6": {
"text": "..."
}
}
};
var section = "paragraph3";
const category = Object.entries(book).find(([, e]) => Object.values(e).includes(section)); /// should return chapter2
if (category) {
console.log(category[0], category[1]);
} else {
console.log("Not Found");
}
Simply replace .values() by .keys() in your code:
var book = {
"chapter1": {
"paragraph1": {
"text": "..."
},
"paragraph2": {
"text": "..."
}
},
"chapter2": {
"paragraph3": {
"text": "..."
},
"paragraph4": {
"text": "..."
}
},
"chapter3": {
"paragraph5": {
"text": "..."
},
"paragraph6": {
"text": "..."
}
}
};
var section = "paragraph3";
const category = Object.entries(book).find(([, e]) => Object.keys(e).includes(section)); /// should return chapter2
if (category) {
console.log(category[0], category[1]);
} else {
console.log("Not Found");
}
here is a solution how to get parent key from children
var book = {
chapter1: {
paragraph1: {
text: '...'
},
paragraph2: {
text: '...'
}
},
chapter2: {
paragraph3: {
text: '...'
},
paragraph4: {
text: '...'
}
},
chapter3: {
paragraph5: {
text: '...'
},
paragraph6: {
text: '...'
}
}
};
var section = 'paragraph3';
const category = Object.entries(book).find(e =>
Object.keys(e[1]).includes(section)
); /// should return chapter2
if (category) {
console.log(category[0]);
} else {
console.log('Not Found');
}

Boolean value from NodeJS webservice is not boolean when using in test

I called a NodeJS webservice :
request({
url: "http://10.210.210.41:3001/trackable/lastPos",
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
async.forEachOf(body, function (vehiculeJSON, cleJSON, cbVehiculeJSON) {
var tabFlotte = vehiculeJSON.flotte;
if (tabFlotte.length > 0) {
var dbJSON = rows.find(function(row) {
return row.num_tag_ip == cleJSON;
});
if (dbJSON != undefined) {
var num_tag_ip = cleJSON, etat = vehiculeJSON.state, coordinates = vehiculeJSON.position, immatriculation = dbJSON.immatriculation, lib = dbJSON.lib, msisdn = dbJSON.msisdn;
if (vehiculeJSON.is_outofarea == true) { // here is the test
...
}
}
}
cbVehiculeJSON();
}, function () {
...
});
} else {
...
}
});
It returns values like this :
{
"TMA0224": {
"zone": 161,
"fixed_at": "2019-12-03T09:55:49.000Z",
"flotte": [
{
"type": "fleet",
"id": "GAN.TELMAPROPRE"
},
{
"type": "fleet",
"id": "TMA"
},
{
"type": "fleet",
"id": "TMA.DVI-MOTOS"
},
{
"type": "fleet",
"id": "TMA.TELMA"
}
],
"state": "MOV",
"numero_tag_ip": "TMA0224",
"immatriculation": "1271TBH",
"ignition": false,
"mileage": 3263,
"heading": 313,
"speed": 2,
"is_outofarea": true,
"position": {
"latitude": -18.90895,
"longitude": 47.536675
}
},
...
}
But at runtime the test never enters the "if" test. But when I replace the test by vehiculeJSON.is_outofarea == "true" then the test succeeds ! So why is the json supposed boolean value transformed to String ?
Try this instead :
if (!!vehiculeJSON.is_outofarea) {
...
}
It should work whether it is a string or a bool.

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

Indeterminate checkboxes with Vue.js

I just started out working with Vue and I'm trying to visualise a nested list.
The list-items should contain triple-state checkboxes:
When a child item is checked, the parent item's checkbox should become 'indeterminate'. When all child-checkboxes are checked, the parent checkbox should also become checked.
When a parent item checkbox is checked, all child item checkboxes (also the ones nested deeper) should be selected too.
I kind of have a working solution (check out this pen or the code below) but the checkbox-logic is still flawed. For this example, checked boxes are green, indeterminate ones are orange and unchecked ones are red.
I've run out of ideas how to fix it. Could someone shed some light on how to accomplish this in Vue?
'use strict';
Vue.component("book-chapter", Vue.extend({
name: "book-chapter",
props: ["data", "current-depth"],
data: function() {
return {
checked: this.data.checked,
indeterminate: this.data.indeterminate || false
};
},
methods: {
isChecked: function() {
return this.checked && !this.indeterminate;
},
isIndeterminate: function(){
return this.indeterminate;
},
toggleCheckbox: function(eventData) {
if (this.currentDepth > 0){
if (!this.data.children) {
this.checked != this.children
} else {
this.indeterminate = !this.indeterminate;
}
}
if (eventData) {
// fired by nested chapter
this.$emit('checked', eventData);
} else {
// fired by top level chapter
this.checked = !this.checked;
this.$emit('checked', {
data: this.data
});
}
},
isRootObject: function() {
return this.currentDepth === 0;
},
isChild: function() {
return this.currentDepth === 2;
},
isGrandChild: function() {
return this.currentDepth > 2;
}
},
template: `
<div class='book__chapters'>
<div
class='book__chapter'
v-bind:class="{ 'book__chapter--sub': isChild(), 'book__chapter--subsub': isGrandChild() }"
v-show='!isRootObject()'>
<div class='book__chapter__color'></div>
<div
class='book__chapter__content'
v-bind:class="{ 'book__chapter__content--sub': isChild(), 'book__chapter__content--subsub': isGrandChild() }">
<div class='book__chapter__title'>
<span class='book__chapter__title__text'>{{data.title}}</span>
</div>
<div class='book__chapter__checkbox triple-checkbox'>
<div class='indeterminatecheckbox'>
<div
class='icon'
#click.stop="toggleCheckbox()"
v-bind:class="{'icon--checkbox-checked': isChecked(), 'icon--checkbox-unchecked': !isChecked(), 'icon--checkbox-indeterminate': isIndeterminate()}">
</div>
</div>
</div>
</div>
</div>
<book-chapter
ref='chapter'
:current-depth='currentDepth + 1'
v-for='child in data.children'
key='child.id'
#checked='toggleCheckbox(arguments[0])'
:data='child'>
</book-chapter>
</div>
`
}));
Vue.component("book", Vue.extend({
name: "book",
props: ["data"],
template: `
<div class='book'>
<book-chapter
:data='this.data'
:currentDepth='0'>
</book-chapter>
</div>
`
}));
var parent = new Vue({
el: "#container",
data: function() {
return {
book: {}
};
},
mounted: function() {
this.book = {
"title": "Book",
"children": [{
"title": "1 First title",
"children": [{
"title": "1.1 Subtitle"
}, {
"title": "1.2 Subtitle"
}]
}, {
"title": "2 Second title",
"children": [{
"title": "2.1 Subtitle",
"children": [{
"title": "2.1.1 Sub-Sub title"
}, {
"title": "2.1.2 Another sub-sub title"
}]
}]
}]
}
}
});
Update: fixed a bug found by #PhillSlevin. See pen here
Check this pen, is it what you want to achieve?
I think you can use either eventbus or vuex to solve this problem,
if you treated every 's section as a component.
'use strict';
var bus = new Vue();
var book = {
"title": "Book",
"children": [{
"title": "1 First title",
"children": [{
"title": "1.1 Subtitle"
}, {
"title": "1.2 Subtitle"
}]
}, {
"title": "2 Second title",
"children": [{
"title": "2.1 Subtitle",
"children": [{
"title": "2.1.1 Sub-Sub title"
}, {
"title": "2.1.2 Another sub-sub title"
}]
}]
}]
};
Vue.component('book', {
template: `
<div class="book__chapter">
<p :class="'book__title ' + status" #click="clickEvent">{{title}} {{parent}}</p>
<book v-for="child in children" :key="child" :info="child"></book>
</div>
`,
props: ['info'],
data() {
return {
parent: this.info.parent,
title: this.info.title,
children: [],
status: this.info.status,
};
},
created() {
const info = this.info;
if(info.children) {
info.children.forEach(child => {
child.status = "unchecked";
// use title as ID
child.parent = info.title;
});
this.children = info.children;
}
},
mounted() {
const vm = this;
bus.$on('upside', (payload) => {
const targetArr = vm.children.filter((child) => child.title === payload.from);
if (targetArr.length === 1) {
const target = targetArr[0];
target.status = payload.status;
if (vm.children.every(ele => ele.status === 'checked')) {
vm.status = 'checked';
} else if (vm.children.every(ele => ele.status === 'unchecked')) {
vm.status = 'unchecked';
} else {
vm.status = 'indeterminate';
}
bus.$emit('upside', {
from: vm.title,
status: vm.status,
});
}
});
bus.$on('downside', (payload) => {
if (payload.from === this.parent) {
if (payload.status === 'checked') {
vm.status = 'checked';
vm.children.forEach(child => child.status = 'checked');
} else if (payload.status === 'unchecked') {
vm.status = 'unchecked';
vm.children.forEach(child => child.status = 'unchecked')
}
bus.$emit('downside', {
from: vm.title,
status: vm.status,
})
}
});
},
methods: {
clickEvent() {
if (this.status === 'checked') {
this.status = 'unchecked';
this.children.forEach(child => child.status = 'unchecked');
} else {
this.status = 'checked';
this.children.forEach(child => child.status = 'checked');
}
const vm = this;
bus.$emit('upside', {
from: vm.title,
status: vm.status,
});
bus.$emit('downside', {
from: vm.title,
status: vm.status,
});
},
}
});
var parent = new Vue({
el: "#container",
data: function() {
return {
book
};
},
});
.book__title.unchecked::after {
content: '□';
}
.book__title.indeterminate::after {
content: '△';
}
.book__title.checked::after {
content: '■';
}
.book__chapter {
display: block;
position: reletive;
margin-left: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<div id="container">
<book :info="book" :parent="'container'"></book>
</div>

Set selected on nested object knockout js

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.

Categories