What is the method for obtaining the viewModel in a Knockout component?

I need to prepopulate a knockout component when the document is ready.

This is the code I have written:

function Finding(id, trigger) {
    var self = this;
    self.id = ko.observable(id);
    self.trigger = ko.observable(trigger);
}

function FindingViewModel() {
    let self = this;

    self.findings = ko.observableArray();

    self.addFinding = function () {
        self.findings.push(new Finding(self.findings().length + 1, ""));
    };
    self.removeFinding = function (finding) {
        self.findings.remove(finding);
        ko.utils.arrayForEach(self.findings(), function (value, i) {
            self.findings.replace(value, new Finding(i + 1, value.trigger()));
        });
    };
    self.update = function (data) {
        var findings = data.findings;
        for (var index = 0; index < findings.length; ++index) {
            var finding = findings[index];
            self.findings.push(new Finding(self.findings().length + 1, finding.trigger));
        }

    };
}

ko.components.register('finding', {
    template: `<table>
            <tbody data-bind="foreach: findings">
            <tr>
            <td><span data-bind="text: id"/></td>
            <td><input data-bind="value: trigger"/></td>
            <td><a href="#" data-bind="click: $parent.removeFinding">Remove</a></td>
            </tr></tbody></table>
            <button data-bind="click: addFinding">Add a Finding</button>`,

    viewModel: FindingViewModel

});

$(function () {
    ko.applyBindings();
    $.getJSON("/_get_findings", function (data) {
        //findingModel.update(data);
    })
});

What is the best way to access the Viewmodel from the finding component in order to update data from within the getJSON function?

Answer №1

Thanks to Jeroen, the code solution appears as follows:

function FindingViewModel() {
    let self = this;

    self.findings = ko.observableArray();

    self.addFinding = function () {
        self.findings.push(new Finding(self.findings().length + 1, ""));
    };

    self.removeFinding = function (finding) {
        self.findings.remove(finding);
        ko.utils.arrayForEach(self.findings(), function (value, i) {
            self.findings.replace(value, new Finding(i + 1, value.trigger()));
        });
    };

    self.update = function (data) {
        let findings = data.findings;
        for (let index = 0; index < findings.length; ++index) {
            let finding = findings[index];
            self.findings.push(new Finding(self.findings().length + 1, finding.trigger));
        }
    };

    $.getJSON("/_get_findings", function (data) {
        self.update(data);
    });
}

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

The Web-application encounters a challenging error of 403() Permission denied

Currently, I'm facing a puzzling situation with my accounting software, Kivitendo. It is hosted on a PLESK Debian12 Server. Strangely, whenever I attempt to select a chart using the magnifying glass icon (please refer to the accompanying image), an un ...

What are the ways to show backend information in a react.js application?

What is the method to display and render data fetched from the backend in react.js? The data retrieved from the backend includes date, time values, and notes. In this scenario, a global variable is used to store the response, which is then assigned to a s ...

Learn how to securely download files from an Azure Storage Container using Reactjs

I'm currently working on applications using reactjs/typescript. My goal is to download files from azure storage v2, following a specific path. The path includes the container named 'enrichment' and several nested folders. My objective is to ...

Utilize JQuery AJAX to retrieve a PHP array and then store it in a JavaScript variable

I am facing a challenge that seems simple to resolve, but it's proving to be quite tricky. Currently, I have a functional PHP file that fetches data from a database and stores it in an array. This file does not require any parameters and the output i ...

Personalized sorting to match the unique rendering of cells in Material UI Data Grid

I have integrated the Material UI V4 Data Grid component into my React Js application. The Data Grid component requires two props: rows (list type) and columns (list type). Below is a sample row item: const rows = [ { id: 1, customerName: " ...

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Use jQuery's post method to send an input file to a PHP file whenever it changes

From my understanding, it seems that $.ajax() is similar to $.post(). I am attempting to use $.post to send an input file to a PHP script in order to upload the chosen image once the user has browsed for it. I'm trying to implement something straight ...

Why is my React build's index.html coming up empty?

I've been working on a React app using Snowpack, and everything seems to be in order. The build process completes successfully, but when I try to open the index.html file from the build folder, the page appears blank. To temporarily resolve this issu ...

struggling with handling form data in Express/Node application

Currently this is my setup: Below is the Post method I am using app.post('/barchartentry', function(req, res){ res.render('barchart', { title: 'EZgraph: Bar Chart', barValues: req.body.myInputs, labelValues: req.body ...

React does not allow _id to be used as a unique key

When I retrieve the categories from my allProducts array fetched from the database using redux-toolkit, I filter and then slice the array for pagination before mapping over it. However, I keep encountering a warning: Each child in a list should have a un ...

What methods can I use to prevent jquery.address from modifying the URL in specific scenarios?

I am utilizing a plugin called jquery.address to manage browser history states on my ajax-heavy website. However, there is a specific scenario where I need to prevent the $.address.change() function from being triggered by a certain link. For instance, in ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

Ways to retrieve the initial key object received through an AJAX request

I have a form with three dynamic dropdowns. The second dropdown depends on the first one, and the third dropdown depends on the second one. Therefore, selecting an option in the first dropdown will automatically populate the next two dropdowns. Below is t ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

Mixing various templates into a single outlet in ember.js

I have been working on an ember application that allows users to create, edit, and delete users, as well as view a list of all users. The app was created by following a tutorial on Ember (as I am still learning), but I am facing an issue. Currently, all th ...

Using ParsleyJS to activate on form fields dynamically created through AJAX requests

My issue arises from having a form that, when a click event occurs, sends an ajax request to another URL. The response from the server is then appended (a series of form inputs) to the end of the current form. The dilemma I am facing is that Parsley, whic ...