Utilizing TypeScript to Populate an observableArray in KnockoutJS

Is there a way to populate an observableArray in KnockoutJS using TypeScript? My ViewModel is defined as a class.

In the absence of TypeScript, I would typically load the data using $.getJSON(); and then map it accordingly.

function ViewModel() {
    var self = this;

    self.list_data = ko.observableArray([]);

    $.getJSON('/Home/Get', function (data) {
        var mapped = $.map(data, function (obj) { return new AClass(obj); });
        self.list_data(mapped);
    });
}

I have attempted to incorporate this data loading process within the constructor of my TypeScript class. However, I am encountering difficulties when attempting to map the JSON data array and store it within the

list_data = ko.observableArray([]);
property. Can anyone provide guidance on how to accomplish this?

class MyViewModel {
    constructor() {
        $.getJSON('/Home/Get', function (data) {
            alert(data);
        });
    }

    list_data = ko.observableArray([]);
}

Thank you for your assistance.

EDIT:

The following is the data received from the server:

[{ "Product": "102289", "ArtworkId": 19431, "IsDownloaded": 1 },
    { "Product": "272203", "ArtworkId": 19423, "IsDownloaded": 1 },
    { "Product": "272222", "ArtworkId": 20306, "IsDownloaded": 1 },
    ...
    { "Product": "862280", "ArtworkId": 19420, "IsDownloaded": 1 }]

Answer №1

If you were to implement this in TypeScript, it might look something like this:

class Model {
    data = ko.observableArray([]);
    constructor() {

        $.getJSON('/Home/Get', data => {
            var mappedData = $.map(data, obj => new AnotherClass(obj));
            this.data(mappedData);
        });
    }
}

This code snippet will compile into the following JavaScript equivalent:

var Model = (function () {
    function Model() {
        var _this = this;
        this.data = ko.observableArray([]);
        $.getJSON('/Home/Get', function (data) {
            var mappedData = $.map(data, function (obj) { return new AnotherClass(obj); });
            _this.data(mappedData);
        });
    }
    return Model;
})();

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

Customize the background color of InfoBox in Google Maps API V3 using a dropdown menu

I'm attempting to dynamically change the background color of an InfoBox by using a Dropdown list (this InfoBox is used to create map labels). I am using google.maps.event.addDomListener, but the values are not returning. Below is my code, can anyone i ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Parse the JSON message using the Boost JSON library

Currently, I am exploring how to utilize boost json along with property trees for decoding a json message. Specifically, my focus is on determining whether the message contains the key "mykey" and, if so, retrieving the corresponding values. Navigating ...

Exploring a JSON object's array for a specific attribute with D3

My force layout data includes: "nodes":[ {"id":"0", "name":"A", "isListedIn":["USSDN","Canadian list"] }, Typically, I would then bind this data to a D3 selection like so: d3.select(body).selectAll(".node").data(graph.nodes).enter() .ap ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

The commitment to Q ensures that errors and exceptions are effectively communicated

Here is a code snippet that I am using to transform a traditional nodejs function into a promise-based one: Object.defineProperty(Function.prototype, "toPromise", { enumerable: false, configurable: false, writable: false, value: function ...

Setting a Validator for a custom form control in Angular: A step-by-step guide

I need to apply validators to a specific control in formGroup from outside of a custom control component: <form [formGroup]="fg"> <custom-control formControlName="custom"> </custom-control> </form> this. ...

I am currently experiencing a problem with deleting documents in Firebase Firestore using React, Typescript, and Redux. Despite the code running, the document continues to exist in

I seem to be encountering an issue that I can't quite figure out. Despite my code running smoothly, I am unable to delete a document from Firestore. The document ID definitely exists within the database, and there are no subcollections attached to it ...

Can someone assist me in understanding the proper syntax for the Node.js function that inserts a document into Watson's Discovery service from the watson-developer-cloud library?

I'm attempting to upload JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK. Here is the relevant code snippet: const DiscoveryV1 = require('watson-developer-cloud/discovery/v1'); const discovery = new D ...

Unable to display images in the ngImgCrop upload preview modal screen

Currently, I am utilizing ngImgCrop to enable an upload preview and square crop feature for profile pictures. Unfortunately, I am experiencing issues where neither the image preview nor the cropping functionality are being displayed. 'use strict ...

What is the best way to deal with empty arrays during serialization of modified form elements only?

Managing a form with numerous multi-select fields can be challenging, especially when dealing with paged ajax. With each select having a unique ID and named accordingly as values[foobar1][], values[foobar2][], values[foobar3][], and so on, it's crucia ...

JS/JQuery: Retrieve value from dropdown list or input field

I'm looking for a way for my user to choose a value from a drop-down menu, but if they can't find the right option there, I want them to be able to input a custom value. I've figured out a workaround by deactivating the drop-down and activa ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Create a JSON structure with nested elements

I've been attempting to create a nested JSON from a simple JSON but haven't been successful yet. Here is the JSON structure I'm trying to convert: [ { "station_id": "ESP0001", "datetime": "2022-1 ...

The type 'string | AddressInfo' does not include a 'port' property and does not have a string index signature

When running in { port }, I encountered the following error: Type 'string | AddressInfo' has no property 'port' and no string index signature. How can I resolve this issue? Code: import * as express from 'express' const app ...

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

Parcel React component library throws an error stating that "require is not defined

Error message: Uncaught ReferenceError: require is not defined at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1 (anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1 First lines of index.js: require("./index.css"); var $cI6W1$lodash = require("lodash&q ...

Using JavaScript to toggle the display of a label element

Greetings everyone! I recently posted a question on this thread about replacing input with javascript, but ended up abandoning that idea. Instead, I decided to explore a different approach... I made the background of my password field transparent and posi ...