Search code examples
javascriptknockout.jsknockout-mapping-plugin

knockout mapping plugin difficulty with observable array


just started working with the mapping plug in for knockout. however after reading the documentation I can't figure out why my observableArray is saying it is undefined.

here is the fiddle. https://jsfiddle.net/zv39qn64/3/

when I run the fiddle I receive ReferenceError: Books is not defined.

JS

$(document).ready(function() {
  getModelFromServer()
});


var data = {
  LibraryName: "My home library",
  Books: [
    { Id : 1, Title : "Oliver Twist" },
    {Id: 2,  Title: "Moby Dick"}
  ]
};


function getModelFromServer() {
  $.ajax({
    type: 'GET',
    cache: false,
    data: data,
    url: '/echo/jsonp/',
    success: function(response) {
    var libraryViewModel = ko.mapping.fromJS(response);
    ko.applyBindings(libraryViewModel);
    }
  });
}

HTML

The library <span data-bind="text: LibraryName"></span>
<ul data-bind="foreach: Books">
<li>
    <span data-bind="text: Id"></span> <span data-bind="text: Title"></span>
 </li>
</ul>

Solution

  • function getModelFromServer() {
    $.ajax({
        type: 'POST',
        cache: false,
        data: {
            json: JSON.stringify(data)},
        url: '/echo/json/',
        success: function(response) {
        var libraryViewModel = ko.mapping.fromJS(response);
        ko.applyBindings(libraryViewModel);
        }
      });
    }
    

    changed only the type to post and the data entry

    https://jsfiddle.net/zv39qn64/4/