This is the continuation of the previous post.
Now that we have the data, and have populating our Model, all that is required is to create the template to use.
If you are new to Knockout, the following sites will become your new best friend
And lets not forget
For this first step, all we want to produce is a list of the policies. To keep it simple for now, will be using a table. All that going to be displaying is the policy number and the policyholder name. What we want is
<table id=""policyInformation"> <thead> <tr> <td>Policy Number</td> <td>Policyholder</td> </tr> </thead> <tbody> <tr> <td>Display policy number</td> <td>Display Policyholder name</td> </tr> </tbody> </table>
To actually template the sample table layout about, only a few minor changes are required
As a reminder, here is the ViewModel that we created in the previous post:
export class Policy { constructor( public Identifier: number, public PolicyNumber: string, public Policyholder: string) { } } export class PolicyViewModel { public Policies: KnockoutObservableArray; public Load() { } }
<table id="PolicyData"> <thead> <tr> <td>Policy Number</td> <td>Policy Holder</td> </tr> </thead> <tbody> <!-- ko foreach: Policies --> <tr> <td><span data-bind="text: PolicyNumber" /></td> <td><span data-bind="text: Policyholder" /></td> </tr> <!-- /ko --> </tbody> </table>
The change to make the table work with Knockout is very simple
The statement indicates the start of the template <!– ko foreach: Policies –>. This is used to bind to the item in the view model: the Knockout Observable array Policies
For each individual row, the data-bind attribute is to bind to the actual element in the Policy object in the Knockout array.
To get it to display, all this is required is some simple jquery after the page loads
<script type="text/javascript"> $(function() { var vm = new MotorDB.PolicyViewModel(); $.when(vm.Load()) .then(function () { ko.applyBindings(vm, document.getElementById("PolicyData")); }); }) </script>
After the DOM has loaded, first create the ViewModel that we created previously. Once the ViewModel is created, call the Load method, which will return the Javascript promise once the Ajax call has been completed.
Once the promise has been received, then we want to apply the knockout bindings. Just pass in the name of the table that we created above, and then Knockout will bind all the data.
Policy data is now displayed in a simple table.
The completed code for this is available on Github
[…] Using Knockout – Part 1 (thesoftwaredudeblog.wordpress.com) […]