简体   繁体   中英

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?

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.

Remove the parenthesis here:

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

See the spec: http://knockoutjs.com/documentation/observableArrays.html

var myObservableArray = ko.observableArray(); // Initially an empty array myObservableArray.push('Some value'); // Adds the value and notifies observers

The reason is self.arnVal is an observable array while self.arnVal() is a simple array (which does not have notification capabilities).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM