Search code examples
javascriptjqueryjsonknockout.jsoracle-jet

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


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?


Solution

  • 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.