Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Set value of observable in asynchronous function

I'm using DevExtreme and knockout. I want to fetch JSON-Data from a server and save it into an observable.

Current approach:

var dataArray = ko.observableArray();
var dataId = ko.observable("");

MyApp.overview = function (params) {
    "use strict"; 

    var viewModel = {
        [...]
    }

    return viewModel;
};

function getDataFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            var entries = $.map(data, function (item) { return new entry(item) });
            // first entry is ID
            for (var i = 1; i < entries.length; i++) {
                dataArray.push(entries[i]);
            }
        }
    });
}

function getIDFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            dataId(data.ID);
        }
    });
}

function entry(data) {
    this.A = data.A,
    this.B = data.B,
    this.C = data.C
}

I'm new to these scenarios, so I'm not sure if my apporach. For testing, I'm calling the functions to get the JSON-Data manually via buttons, and I get the needed data, but the observables both contain this:

function c(){if(0<arguments.length)return c.tb(c[E],arguments[0])&&(c.ga(),c[E]=arguments[0],c.fa()),this;a.l.oc(c);return c[E]}

What am I missing? Or is this approach bad practice in general?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

How I do it is by using the Knockout Mapping Plugin and the fromJSON command (you might need to use fromJS depending on your data format) this maps the data as it comes from the source.

function getDataFromJson() {
    $.ajax({
        url: 'http://localhost:56253/test/3?format=json',
        dataType: 'json',
        success: function (data) {
            ko.mapping.fromJSON(data, {}, self.dataArray);
        }
    });
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!