How to bind Json data returned by a asynchronous call to a knockout observableArray correctly Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to bind Json data returned by a asynchronous call to a knockout observableArray correctly without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to get a json object by an ajax call, and put it into a knockout observable.

var self = this;
this.arnVal = ko.observableArray([]);

var promise = $.getJSON('../../url/to/my/api');

promise.done(function(data) {
         console.log(data);
         console.log(data["metricValues"]);                
         self.arnVal().push(data["metricValues"]);
         console.log(self.arnVal());                                     
      });

The expected values are getting printed correctly by the console logs inside the promise.done() function call. That is, the data is in the correct Array format expected by the Oracle Jet component I am binding it with.

This code is in a Knockout component javascript file, which I am using in a HTML file somewhere else as a part of a Knockout component. In the HTML file of the component, I am using arnVal to populate a Oracle Jet chart.

But the chart never gets populated with the updated arnVal data as obtained from the getJSON call.

What am I doing wrong?

Answer

Just remove the extra parens from self.arnVal().push(...).

self.arnVal.push(data["metricValues"]);

Currently the parens are unboxing the observable array and pushing the new item to the underlying javascript array. This bypasses knockout’s event triggers.

We are here to answer your question about How to bind Json data returned by a asynchronous call to a knockout observableArray correctly - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji