3

Having a go at playing with Knockout and I'm having problems with pushing to an observable array. My code below fetches some json data from the server on a button click, it's returning an array of objects. The first console.log consoles out fine, I have my array of objects just fine and dandy.

I can't seem to push each object onto my observable array, however. The console shows me empty arrays. I've tried several variations, but feel like I'm just missing something simple, yet I'm having a hard time tracking it down.

What I'm trying to do is load up some data from the server, put it in an observable array that I can bind to a template and do something like a foreach on to output the contents of the array.

$(function() {
    $('#load').click(function() {
        $.getJSON('/PreferredDrugList/service/preferredDrugs/y', function(data) {
            $(data.preferredDrugs).each(function(index, obj) {
                console.log(obj);
                $('#result').append('<p>' + (++index) + ') ' + obj.drugName + ' : ' + obj.dosageFormDesc + '</p>');

                myViewModel.drugList.push(obj);
                console.log(myViewModel.drugList);
            });
        });//end getJSON
    });//end load

});//end ondomready

var myViewModel = {
    drugList: ko.observableArray()  //list of drug names
};

ko.applyBindings(myViewModel);
magenta placenta
  • 1,461
  • 7
  • 22
  • 34

1 Answers1

2

Take a look at the following: http://jsfiddle.net/qszZD/

You mentioned above in your comment that you needed to get your foreach to work. Hopefully this is a good start for you. I am using a few things, which you may or may not want to take care of:

knockoutJS.mapping

I'm using the optional mappingOptions to define computed observables based on the data returned from the mapping library. By using KO mapping, avoid needing to manually push the elements into your observable array, the mapping library will handle that for you automatically and also gives you the ability to extend your model further by providing mapping options to create additional computed fields.

Let me know if you have any questions.

Jeff Woodard
  • 647
  • 8
  • 15