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

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

Encountered a NullPointerException while attempting to generate an array from a MySQL database

I encountered a NullPointerException while attempting to create a multiple array of data from MySQL. The error seems to be originating at this line of code: JSONObject jsonResponse = new JSONObject... NewsFeed.java public class NewsFeed extends Fragment ...

Looking to optimize the JavaScript code for improved performance speed

Is there a more efficient way to avoid writing the same lines of code repeatedly without compromising performance? I've attempted using a for loop to categorize fields as 'mandatory' or 'optional', but it still requires duplicating ...

Utilize mapping for discriminated union type narrowing instead of switch statements

My objective is to utilize an object for rendering a React component based on a data type property. I am exploring ways to avoid utilizing switch cases when narrowing a discriminated union type in TypeScript. The typical method involves using if-else or sw ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

Leveraging the expand function for pagination through recursive invocations

I am currently working on retrieving data from a third party API that necessitates manual management of paging by keeping track of the number of records retrieved versus the total number of records available. In attempting to handle this, I experimented w ...

Retrieve a PHP file utilizing Javascript or JQuery

Is there a more straightforward method than using ajax to retrieve the contents of an HTML or PHP file and place it within a div on the current page? I am familiar with the process through ajax, but I am curious if there is a simpler alternative that doe ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...

The designated type member is not compatible with LINQ to Entities. Utilizing JSON, KendoUI, and AJAX

Hello everyone, thank you for taking the time to assist me. I'm currently exploring KendoUI and attempting to bind a Grid using AJAX, but I encountered an error: The specified type member 'getFullName' is not supported in LINQ to Entities. ...

Finding Location Information Based on Latitude and Longitude Using Jquery

Does anyone know of a reliable solution or Jquery plugin that can provide location details based on latitude and longitude coordinates? I heard about the Google Reverse Location API but hoping for a pre-made option. I'm not sure if there are any free ...

The switch statement is not functioning properly when the button is pressed

I am trying to trigger an alert inside a switch statement when I click a button, but for some reason, it is not working. Even if I simply have an alert in the previous function, there is no output on my website. What could be causing this issue? Here is ...

I'm having trouble with the routing of a Node.js REST API built with Express and Mongoose

I am currently in the process of constructing a RESTful webservice by following a tutorial that can be found at: However, I have encountered an issue where it is returning a CANNOT GET/ reports error. Despite my efforts to troubleshoot and rectify the pro ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function sti ...

Is Volley equipped with built-in support for JSON arguments and string responses?

I am trying to send a JSON payload via a server POST request and receive a string response. After researching extensively, it appears that doing this with the Volley library is not straightforward unless I create a custom request (which I find daunting). ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

Tips for displaying a category name only once if it has already been rendered in a map function

My scenario involves a variety of categories in which pharmaceutical drugs are classified. Each individual drug belongs to a specific class. Currently, my code iterates through all the categories from the category array and places drugs underneath them if ...

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

MaterialUI Divider is designed to dynamically adjust based on the screen size. It appears horizontally on small screens and vertically on

I am currently using a MaterialUI divider that is set to be vertical on md and large screens. However, I want it to switch to being horizontal on xs and sm screens: <Divider orientation="vertical" variant="middle" flexItem /> I h ...

Updating a model within an ng-repeat directive from external sources

Within my controller, there is a repeater where each item has its own unique status: <div ng-controller="..."> <div ng-repeat"...">{{status}}</div> </div> Currently, changing the status within the repeater by using status = &apo ...