1
votes

I am learning Knockout and cannot get Knockout.mapping.fromJS to work. Here is my code:

$.getJSON("data/status.json", function(data) {
        var members = ko.mapping.fromJS(data);
});
ko.applyBindings(members);

I am using a template. Here is the template:

<script type="text/html" id="membersTemplate">
    <li data-bind="text: members.dname"></li>
</script>

And the markup...

<div id="members">
<h2>Members</h2>
<ul data-bind="template: {name: 'membersTemplate', foreach: members}"></ul>
</div>

The JSON data loads correctly, but the "members" object is "undefined." (Members.dname is one object property among many.)

Can anyone tell me what I'm doing wrong? Thanks in advance!

1

1 Answers

0
votes

More than happy: your members variable is outside of scope, so it gets lost after our AJAX call completes. You want something either like this.

$.ajax({url:"/echo/json/", data:json, type:"POST", success:function(data) {
  var viewModel = ko.mapping.fromJS(data);
  ko.applyBindings(viewModel)
}});

So you apply the bindings inside of the scope of the AJAX call or something like this.

var self = this
self.members = ko.observableArray([]);
$.ajax({url:"/echo/json/", data:json, type:"POST", success:function(data) {
  var members = ko.mapping.fromJS(data);
  self.members(members);
}});
// do the binding elsewhere

Which binds your response inside a closure. Remember that an AJAX call is a promise pattern, so you really don't know when the response is completed. Here's a code with a working example.