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

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

Is there a way to retrieve values from a different menu without the need to refresh the page?

Whenever a radio button is clicked on a form, a popup menu is displayed. The popup menu is implemented using the Bootstrap module. However, there is an issue where selecting an option from the popup menu causes the form to reset, resulting in the loss of ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

ASP.NET page experiences issues with executing Javascript or jQuery code

Having trouble with client scripts not functioning correctly on a child page that utilizes a master page. Looking for help to resolve this issue. <%@ Page Title="" Language="C#" MasterPageFile="~/Store.Master" AutoEventWireup="true" CodeBehind="NewSt ...

Activate the search function once the user has finished entering text

Currently facing the following issue: Within my JavaScript file, I have the below code snippet, termChange(evt) { this.rows = []; this.searchTerm = evt.target.value; this.getCases(); } This section of code clears out the ...

Maxlength and Minlength attributes are not considered when using input type=“number”

Why is the maxlength attribute not functioning properly for this input element? <input type="number" maxlength="5" maxlength="10" /> ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

Transmit an array in a post request with Node.js using the application/x-www-form-urlencoded content type

After attempting to send a post request to an API with post parameters as an array, I encountered difficulties. Here is how it can be done using cURL: curl http://localhost:3000/check_amounts -d amounts[]=15 \ -d amounts[]=30 I then tried to ach ...

Utilizing various directives with distinct scopes for a single element

Is it possible for an element to have multiple directives with their own unique scopes? For example, let's consider a custom directive's child element with the controller's scope along with another directive (such as "ng-class"): <custo ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...

Having trouble with a switch statement in Javascript that is unable to find a case for "none."

In my code, I am checking to see if there is a ball in a specific map point and then changing the color of the pixels where the ball is located to match the color of the ball. Here is my code snippet: function UpdateColorInMapPoints(mapPointIndexs) { / ...

I successfully converted a d3 chart to a base64 image format and now I am looking to share it on Facebook using either client-side JavaScript or Angular

After generating a base64 image from a cool d3 chart, my next challenge is figuring out how to share it on Facebook using either client-side javascript or Angular. Any suggestions? ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Seeking an efficient localStorage method for easy table modification (HTML page provided)

Currently, I am in the process of developing a custom 'tool' that consists of a main page with a menu and several subpages containing tables. This tool is intended for composing responses using prewritten components with my fellow colleagues at w ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...