简体   繁体   中英

push json to knockout observable array

I have radio buttons which are observable and depending on the value i want to trigger a GETJSON method to return my data and then push it to an observable array that i am displaying as a list. The error i am getting is Cannot read property 'push' of undefined. Here is my Fiddle

How do i get this Data to my observable Array after the radio button is clicked triggering the getjson method?

self.currentAnswer = ko.observable();
    self.recipientList = ko.observableArray([]);
self.currentAnswer.subscribe(function (newValue) {
    if (newValue == 'Internal') {
        $.getJSON('GetInfo', function (data) {
            var result = $.parseJSON(data);

            self.recipientList.push(result);


        });

I updated your Fiddle so that it works. Basically you need to call self.recipientList.push.apply(self.recipientList, result);

https://jsfiddle.net/jsw1ezut/9/

Things to consider:

  • $.getJSON() will parse the JSON for you, you never need to do that yourself. This is also true for $.get() . (*)
  • Knockout observables are functions. You can use them as callbacks. (**)

With this knowledge:

self.recipientList = ko.observableArray();
self.currentAnswer = ko.observable();
self.currentAnswer.subscribe(function (newValue) {
    if (newValue == 'Internal') {
        $.get('GetInfo').done(self.recipientList);
    }
});

(*) If you do not get parsed JSON in your success callback, fix the Content-Type header of your response.

(**) If you call an observable and pass a value as first argument, it will store that value. Coincidentally jQuery calls Ajax success callbacks passing the returned value as the first parameter. Perfect fit.

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