Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in the "Choice" object contains an array of "Stage" objects, each with properties like id, name, & value. Each "Choice" object progresses through stages from "First Stage" to "Fourth Stage," allowing users to select a "Stage" from a dropdown list and save it. The "currentStageId" property stores the id of the stage object the respective "Choice" object is currently in.

Note: Different choices can have different types of stages for simplicity.

For Choice 1, the current saved stage is 4.

var data = [
new Choice({
    id: 1,
    name: "One",
    stages: [
    new Stage({
        id: 1,
        name: "First Stage",
        value: 25
    }),
    new Stage({
        id: 2,
        name: "Second Stage",
        value: 50
    }),
    new Stage({
        id: 3,
        name: "Third Stage",
        value: 75
    }),
    new Stage({
        id: 4,
        name: "Fourth Stage",
        value: 100
    })],
    currentStageId: 4

}),
new Choice({
    id: 2,
    name: "Two",
    stages: [
    new Stage({
        id: 1,
        name: "First Stage",
        value: 25
    }),
    new Stage({
        id: 2,
        name: "Second Stage",
        value: 50
    }),
    new Stage({
        id: 3,
        name: "Third Stage",
        value: 75
    }),
    new Stage({
        id: 4,
        name: "Fourth Stage",
        value: 100
    })],
    currentStageId: 3

}),
new Choice({
    id: 3,
    name: "Three",
    stages: [
    new Stage({
        id: 1,
        name: "First Stage",
        value: 25
    }),
    new Stage({
        id: 2,
        name: "Second Stage",
        value: 50
    }),
    new Stage({
        id: 3,
        name: "Third Stage",
        value: 75
    }),
    new Stage({
        id: 4,
        name: "Fourth Stage",
        value: 100
    })],
    currentStageId: 2

})];

The following are the "Choice" & "Stage" models for holding data and ViewModel for binding:

function ViewModel(data) {
    var self = this;
    self.choices = ko.observableArray(data);
    self.selectedChoice = ko.observable();
}

function Choice(data) {
    this.id = data.id;
    this.name = data.name;
    this.selectedStage = ko.observable(ko.utils.arrayFirst(data.stages, function (item) {
        return item.id === data.currentStageId;
    }));
    this.stages = ko.observableArray(data.stages);

}

function Stage(data) {
    this.id = data.id;
    this.name = data.name;
    this.value = data.value;
}
ko.applyBindings(new ViewModel(data));

Here is my view:

<select data-bind="options: choices, optionsText: 'name', value: selectedChoice"></select>
<select data-bind="options: selectedChoice().stages, optionsText: 'name', value: selectedChoice().selectedStage"></select>

Knockout.js 2x version:

  1. Pre-selection of saved stage is working.
  2. Selected stage for choice is updated into underlying observable.

Here is the Working sample with KO 2x in js

Knockout.js 3x version:

  1. Pre-selection of saved stage is not working.
  2. Selected stage for choice is not preserved. When choice is changed, the selectedStage is set to the first item in the dropdown list each time the choice is changed.

Here is the Working sample with KO 3x

Finally, the actual question:

  1. Why does the same code behave differently with two versions of KO? Am I missing something new in KO or is it a bug in KO?
  2. What code changes should be made to produce the same functionality as in the later version of KO using the latest version of KO? My project is being developed with the latest version of Knockout.js 3.1.0, and I don't want to switch back to an older version for this functionality.
  3. Which behavior of KO version is correct, 2x or 3x? What is happening internally that causes these discrepancies in behavior?

Thanks in advance.

Answer №1

It seems like the issue is connected to 2. The way bindings are refreshed has changed
Now, you need to make sure that selectedChoice is outside of the options binding, for example:

<div data-bind="with: selectedChoice">
   <select data-bind="options: stages, optionsText: 'name', value: selectedStage"></select>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Json parsing to extract and display precise data

This is a snippet of JSON code and I am attempting to execute it: Sub test() Dim req As New MSXML2.XMLHTTP60 Dim URL As String, ws As Worksheet Dim json As Object, r, r1 As String URL = "https://www.nseindia.com/api/quote-equity?symbol=DIVISLAB" ...

The functionality of Ajax is limited when it comes to handling multiple div elements at the same

Seemingly silly question ahead, but I've been grappling with it for days to no avail. If anyone can help me solve this, please state your price and provide your PayPal details – the money is yours :). What I'm trying to achieve is to add a "Add ...

Another problem with CORS again?

My rails application uses the host http://myhost.dev to search for music through the vk.com API. The API provides a search method called audio.search. Below is the code snippet from my search.js.erb file which is executed via a remote link to the search ac ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Passing an array from JavaScript to PHP and then storing it as a .json file

Query I am trying to pass an array to PHP and save it in a data.json file. However, the data.json file is being created but showing Null as output. I have spent about 2 hours on this code, checked numerous solutions on SO, but nothing seems to work. As I ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Namespacing is not applied to dynamic modules in Vuex

I've been tackling a modular vue application that enrolls the modules during compile time. Take a look at the code snippet below - app.js import store from './vue-components/store'; var components = { erp_inventory: true, erp_purc ...

Why doesn't AngularJS validation function properly with input elements of type "number"?

Struggling with Angularjs validation here. Ng-pattern seems to work fine only when the input type is text. However, when the input type is number, ng-pattern doesn't seem to work, although required, min, and max attributes still function. <input t ...

Leveraging JavaScript Fetch() and formData() for Database Updates

As I delve into my JavaScript project, utilizing the fetch() method, I find myself facing a puzzling situation. Despite having a grasp on the basics of fetch and formData, the code in question appears needlessly complex for its intended purpose, leaving me ...

utilizing array.map() to nest multiple layers of arrays

I am facing a challenge with a JavaScript array structure that contains three top-level objects. Each of these objects has an "teamLineup" array, which in turn holds two more objects named "team". These "team" objects have another array called "starters", ...

When an external image is dragged over, include the class in the drop area of the file input

Hey, does anyone know how to use Jquery to add a class when an element is being dragged over a drop area? Here's the HTML code I'm working with: <div class="upload"> <form action=""> <input class="uploadfile" type="file" ...

When the page loads, the HTML side menu will automatically scroll to the active item in a vertical

My website features a vertical side menu with approximately 20 items. The issue I am facing is that when a user clicks on an item, the destination loads but the side menu must be manually scrolled to find the active item if it's located at the bottom ...

Storing query for later utilization using form and javascript

I have implemented a function to create charts using the following code snippet: $('#button_submit').click(function() { var start_date = $('#start_date').val(); var end_date = $('#end_date').val(); var type = $( ...

Syntax for the "data" parameter in jQuery.ajax

I am attempting to send the contents of a JavaScript variable to the server for further processing. While I have no issue passing static strings, I encounter a problem when trying to pass a variable containing a string as the WebMethod fails to execute. He ...

Is there a feature similar to Nuxt.js' auto-register in Next.js?

My Journey as a Beginner Being a beginner in the tech world, specifically in full-stack development (although I'm about 8 years behind), I find myself grappling with the decision of what to focus on learning. Vue and Nuxt.js are fantastic technologi ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

What is the significance of employing the `var` keyword in Vue.js?

As I dive into tutorials and browse through code snippets while immersing myself in learning this framework, I've noticed a common trend - the use of var for declarations. This practice seems prevalent across resources, including the official Vue docu ...

What is the best way to showcase a collapsible tree using AngularJS and Bootstrap?

I'm currently working on a web application that requires the display of a tree structure using lists. Here is the basic outline: * Node 1 * Node 1.1 * Node 1.1.1 * Node 1.1.1.1 * Node 1.1.2 * Node 1.2 http://jsfid ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Toggling checkboxes using Angular framework

Within my form, there is a table with checkboxes in each column. The table consists of 3 <tr> elements, and each <tr> uses ng-repeate to call the webservice and display clone data (in JSON format). Upon clicking a checkbox, I create a JavaScrip ...