Unique Version: "Struggling with unresponsive values while using observable arrays and forEach binding? Here's

I am currently utilizing knockout js in conjunction with asp.net mvc (vs2013) and entity framework. Initially, I have an index page (masterViewModel) where I define all my sub view models.

Furthermore, I have a viewmodel and a function that sends an ajax call to the server side, retrieves data from the server, inserts it into an observable array, and binds the elements of that array to the view. The data fetched from the server includes three objects. While the binding process is successful, instead of displaying three distinct assistant driver names on the view, it repeats the same value thrice (object 2) after looping through object 0 and 1. Presently, my output looks like this:

smith smith smith

This is my ajax call using knockout:

function populateDrivers() {
    if (!masterViewModel.isAuthenticated()) return;

    $.when(getSecureData("/api/Drivers/?driverId="))
    .done(function (resp) {
        masterViewModel.vehicleDetail.assistantDriverList(resp.assistantDriverList)

       ko.utils.arrayMap(resp.assistantDriverList, function (obj) {
       //ko.utils.arrayForEach(resp.assitantDriverList, function (obj)
       //arrayMap
       masterViewModel.FleetInfoVM.vehicleDetail.assistantDriverName(obj.assistantDriverName);
       masterViewModel.FleetInfoVM.vehicleDetail.carRegNumber(obj.CarRegNumber);
       masterViewModel.FleetInfoVM.vehicleDetail.make(obj.Make);
       masterViewModel.FleetInfoVM.vehicleDetail.Model(obj.Model);      
        });

    });

}

And this is the HTML binding:

<table style="table-layout: fixed" class="table table-striped table-bordered">
<thead>
<tr>
    <th>Assistant Name</th>

</tr>
</thead>

<tr>

    <td data-bind="text: $root.FleetInfoVM.vehicleDetail.assistantDriverName"> </td>

    <td class="td-actions">
        <a class="btn btn-small" data-bind="click: $root.vehicleDetail.edit" title="Edit">
            <i class="icon-edit"></i>
        </a>
        <a class="btn btn-small" ">

        </a>
        <a class="btn btn-small">

        </a>
    </td>
</tr>
</tbody>
</table>

Below are my defined view models:

function MasterViewModel() {
        var pvm = this;
        mvm.loginVM = new LoginViewModel();
        mvm.VehicleVM = new vehicleViewModel();
        mvm.topManagerVM = new TopManagerViewModel();
        mvm.FleetInfoVM = new FleetInfoViewModel
    }

   MasterViewModel = new MasterViewModel();
   ko.applyBindings(MasterViewModel, document.getElementById("htmlTop"));


FleetInfoViewModel
=========================================================================

function FleetInfoViewModel
{
  var fiv = this; 

   fiv.branch id = ko.observable(0);
   fiv.branch name = ko.observable(0);
   fiv.location = ko.observable("");
   fiv.driverDetail = new DriverViewModel();
   fiv.vehicleDetail = new vehicleViewModel(); 

}
function DriverViewModel() {
    var drv = this;
    drv.driverId = ko.observable(0);
    drv.driverName = ko.observable("");
}
function  vehicleViewModel{
    vvm.assitantDriverList =  ko.observable([]);
    vvm.assistantDriverName = ko.observable("");
    vvm.regNumber = ko.observable(0);
    vvm.make = ko.observable(""); 
    vvm.model = ko.observable("");
   }

Answer №1

It seems that the issue lies within your implementation of arrayMap. While you are iterating through the results, you're essentially just updating the same object repeatedly, leading to overwriting the result in each iteration. To resolve this, consider creating an instance of vehicleViewModel inside the loop and adding it to an observableArray like this:

var vehicleList = ko.observableArray();

// Use arrayMap to iterate through assistantDriverList 
// Creating a new instance of vehicleDetail viewModel for each item.
vehicleList = ko.utils.arrayMap(resp.assistantDriverList, function(obj) {
    var vehicleDetail = new vehicleViewModel();
    vehicleDetail.assistantDriverName(obj.assistantDriverName);
    vehicleDetail.carRegNumber(obj.CarRegNumber);
    vehicleDetail.make(obj.Make);
    vehicleDetail.Model(obj.Model);      
    return vehicleDetail;
});

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

Securely verifying secret and payload with HMAC in Symfony version 5.4

My current JavaScript code is executing a POST API call to my designated endpoint: const payload = { course: args, recipient: roomId }; const signature = this.calculateSignature(JSON.stringify(payload), secret); const response = await fetch(`https:/ ...

Having trouble launching the react app with npm start command

Attempting to launch a react app created by someone else. The instructions provided stated that in order to start it, I need to follow these steps To initiate the webpack dev script, execute npm start [appname]. The term [appname] corresponds to an appli ...

What could be causing the issue with npm install packages not functioning properly?

Currently, I am in the process of setting up and deploying a particular git repository locally: https://github.com/maxie112/gatsby-ecommerce-theme I am strictly adhering to the instructions provided for Mac OS. Here are the encountered error logs; maxden ...

Tips on combining two objects in an array with indexing

https://i.sstatic.net/XL2qb.pngI am facing an issue with my reducer that is altering the array structure to [{}] or [{},{}] from [0:{}] or [0:{},1:{}] After this modification, I am unable to concatenate to the original array. Is there a way to resolve thi ...

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

Ways to efficiently insert a single element into an array multiple times simultaneously

Can you please help me improve my function that displays the number of coins corresponding to a certain value? For example, an input of 56 should return [25, 25, 5, 1]. I am facing two challenges: 1) How can I display multiple instances of the same coin i ...

Sorting in Vuejs fails to function properly when a filter is applied

Having recently delved into Laravel and Vue, I am eager to develop a site for our Intranet. Pulling data from the Laravel database has been successful, displaying the data works well, and the search functionality is also up and running smoothly. However, I ...

Exploring ways to access an element's background color through JavaScript

Is there a way to access an element's CSS properties that are set by a class name in JavaScript? In the case of the first div element, I have applied a "red" class which sets its background color to red. However, when I try to access the div's b ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Error: The page refreshes when attempting to edit a row in the datatable using Datatable.js

https://i.sstatic.net/huLJW.jpg https://i.sstatic.net/20yYX.jpg Snippet <script type="text/javascript> $(function() { // $.noConflict(); $('#customerGrid').DataTable({ "columnDefs": [ ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Creating nested routes with parameters in NestJS is a powerful feature that allows for dynamic routing

I have a requirement to create an API with routes that share a common URL part along with a parameter. For my particular case, the routes should follow this structure: /accounts/:account/resource1/:someParam /accounts/:account/resource2/:someParam/whate ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

Authenticate through navigation on an alternate component

I am in the process of developing a user interface that includes a side navigation and header bar. However, if the user is not logged in, I wish to redirect them to the login page. The primary component structure is as follows: class App extends Componen ...

Modify: "Alter the background color of the parent container for elements that are deemed invalid during

I am currently working on implementing asp.net's built-in validation feature to indicate required fields, but I want to take it a step further by not only displaying a message but also changing the background color of the parent div containing the inv ...

Path taken to reach the view requested by Node.js server

Snippet of Controller Code: bina: function(req, res) { var request = require('request'); request({ url: 'http://localhost:3000/bina/', method: 'GET', }, function(err, res, body) { ...

What is the process for encrypting data with javascript and decrypting it with php?

Looking for a way to encrypt data with a JavaScript function to use in a URL passed through an ajax GET request? For example, you could have encrypted data like TDjsavbuydksabjcbhgy which is equivalent to 12345: http://sample.com/mypage/TDjsavbuydksabjcbh ...

What is the process for integrating GitHub repository code into my client-side JavaScript application?

I am attempting to incorporate the GitHub repository "zipcelx" into my client-side JavaScript, but all I see is an option to download it from npm, which I do not understand. It would be helpful if someone could explain how a module meant for client-side us ...

What is the best way to implement the v-for loop in a Vue.js application?

I am currently working with a loop that contains four inputs. I am looking to assign separate id values from the loop to each of these inputs. How can I achieve this? click here for image click here for image While running a loop, I have only one input th ...

"Incorporating Node.js (crypto) to create a 32-byte SHA256 hash can prevent the occurrence of a bad key size error triggered by tweetnacl.js. Learn how to efficiently

Utilizing the crypto module within node.js, I am creating a SHA256 hash as shown below: const key = crypto.createHmac('sha256', data).digest('hex'); However, when passing this key to tweetnacl's secretbox, an error of bad key siz ...