1
votes

Edit Looks like I got it loading from the server now. If anyone sees any issues with this, would love to hear about them.

Having some issues getting the knockout mapping plugin working. I can get this working with static data with no problems, see http://jsfiddle.net/RH9wQ/

When I try to load in data from the server, it doesn't seem to work, though. Below is the bare bones code I'm using. The data in the jsfiddle is the exact data that's being returned from my server. Am I missing something completely obvious?

What I'm doing is loading in different drugs based on alpha buttons that are clicked. So click on "y" and get a list of drugs that start with y, click on "z" and get a list of drugs that start with z. When the buttons are clicked/data is loaded, I want to replace my viewModel data with what's coming in from the server.

Also, note the console on the jsfiddle page, data looks fine (8 array elements and count=8), but note the console of the viewModel, preferredDrugs and count are different, anyone know why this is?

$(function() {
    $('.load').click(function() {
        var $letter = $(this).attr('value');

        //show spinner
        $('#loading').show();

        //load in drug list data
        $.getJSON('/PreferredDrugList/service/preferredDrugs/' + $letter, function(data) {
            //hide spinner
            $('#loading').hide();

            console.log(data);
            //create observable properties for each of the properties on data
            ko.mapping.fromJS(data, viewModel);
            console.log(viewModel);

        });
    });

});//end ondomready

//default data
var data = {
    preferredDrugs: [],
    count: 0
};

var viewModel = ko.mapping.fromJS(data);

ko.applyBindings(viewModel);
1

1 Answers

5
votes

When updating an existing view model using ko.mapping you can also try:

ko.mapping.fromJS(data, {}, viewModel);

..instead of..

ko.mapping.fromJS(data, viewModel);

Also, note the console on the jsfiddle page, data looks fine (8 array elements and count=8), but note the console of the viewModel, preferredDrugs and count are different, anyone know why this is?

Yes, the original preferred drugs is a normal array while the new preferred drugs is an observable array. An observable array will look like an empty array if you try to access it directly. However, observables are functions and need to be treated as such.

So...

console.log(myViewModel.preferredDrugs);

...returns an empty array, whereas...

console.log(myViewModel.preferredDrugs());

...returns the actual array.