codedog
codedog

Reputation: 2508

Knockout mapping of nested array

This is my javascript that grabs the data and calls the mapping:

function loadData() {
    currentViewModel.isLoading(true);
    $.get('/api/myevents/' + eventId, null, function (data) {
        var details = ko.mapping.fromJS(data);
        currentViewModel.eventDetails(details);
    });
};

var viewModel = function () {
    var _self = this;
    this.eventDetails = ko.observable(null);
    this.isLoading = ko.observable(false);
    this.addShow = function () {
        addShowDialog();
    };
};

var currentViewModel = new viewModel();

ko.applyBindings(currentViewModel);

loadData();

It seems to work okay until I added an array into the data that is returned. For some bizarre reason it doesn't get mapped by knockout.

I have attached screenshots of the objects either side of the mapping. I'm new to knockout in general, have I missed something fundamental here?

Thanks.

Data returned from server Data mapped by knockout

Upvotes: 2

Views: 2170

Answers (1)

John Earles
John Earles

Reputation: 7194

Are you judging failure by the Shows: Object[0] and length: 0? If you look at _latestValue you will see Array[5]. An Array is mapped to an ObservableArray, which is a function. You have to call the function - Shows(), in this case - to access the real array inside.

Here is a fiddle that shows that array mapping is working fine:

http://jsfiddle.net/jearles/VyH6y/

You can play with this sample to map to your exact scenario.

Upvotes: 3

Related Questions