0
votes

I'm using the latest KO Mapping Plugin. The idea is the Details section should be populated with JSON data retrieved from Ajax Call.

var supervisorVM = {
        supervisor: ko.observable()
    };

-----------code to call custom data service which returns JSON---
     if (supervisorDetails) {
        $('#Detail').show();
        supervisorVM.supervisor = ko.mapping.fromJS(supervisorDetails);
        ko.applyBindings(supervisorVM, document.getElementById("Detail"));
    }



<div id="Detail" class="side-widget" style="display:none">
    <h2>Details</h2>
    <strong>
        Supervisor<br>
        <span data-bind="text: supervisor.FullName"></span><br/>
    </strong>
    <span data-bind="text: supervisor.PhoneNumber"></span><br/>
    <a data-bind="text: supervisor.Email, attr: { href : 'mailto:'+supervisor.Email() }"></a>
</div>

Everytime I run the Detail section doesn't get populated with supervisor details i.e. Fullname and Phone Number.

I debugged and confirmed that supervisorVM.supervisor is populated but data bind doesn't work.

Also tried below no luck:

supervisorVM.supervisor(ko.mapping.fromJS(supervisorDetails));

I spent more than 2 hours already, can someone please help what have I done wrong?

Thanks.

1
well its working fine for me check here jsfiddle.net/supercool/74dh736s/16 . if you can reproduce the issue in fiddle its easy to sort it out. - super cool
The fact that you're making a query call to show the Detail div rather than using a boolean observable along with applying the binding so specifically to the DOM element makes me think you aren't using knockout appropriately and is probably the reason behind most of your struggle. - Spencer Ruport

1 Answers

1
votes

Your bindings such as supervisor.Fullname are defined incorrectly - you are looking for a property 'Fullname' on the observable function. It should be supervisor().Fullname.

Try wrapping the fields in a with: supervisor binding. This has the nice side effect that the fields aren't rendered, as long as your AJAX call hasn't returned and added content to supervisor:

<div id="Detail" class="side-widget" style="display:none" data-bind="with: supervisor">
    <h2>Details</h2>
    <strong>
        Supervisor<br>
        <span data-bind="text: FullName"></span><br/>
    </strong>
    <span data-bind="text: PhoneNumber"></span><br/>
    <a data-bind="text: Email, attr: { href : 'mailto:' + Email() }"></a>
</div>

Also, do not replace observables, as you do here:

supervisorVM.supervisor = ko.mapping.fromJS(supervisorDetails);

Instead, replace their contents:

supervisorVM.supervisor( ko.mapping.fromJS(supervisorDetails) );

Your markup is already bound against the old observable you assigned with supervisor: ko.observable(). You can replace that observable with a new one, but your markup remains bound to the old one — it will never update again.