Thursday, 10 September 2015

Basic usage of Knockoutjs in a website

Setup the project to use Knockout in a Visual Studio project, see: Setting up a Visual Studio Project for use with Knockout


1. In this example, the styles and the javascript were declared inline in the document
2. Add the styles in the <style> tag in the header,
3. Add the View (the HTML) in the <body> of the document
4. Add the Model in a <script> tag in the body of the page
5. Add the ViewModel, also in the above <script> tag
6. Bind the ViewModel, also in the above <script> tag
7. See the complete example below
8. Set your Index page as the default page for the project
9. Run the project and see what Knockout can do for you


<!DOCTYPE html>
<html>
<head>
   <title>Using KnockoutJS in a Web Page</title>
   <meta charset="utf-8" />
   <script src="Scripts/knockout-3.3.0.js"></script>
   <style>
       body {
           margin: 10px;
       }
       span {
           margin: 0 10px 0 0;
       }
       .descArea {
           padding: 10px;
           background-color: lightgray;
           border: black 1px solid;
       }
   </style>
</head>
<body>

   <span data-bind="text: shortDesc"></span>
   <div data-bind="text: description" class="descArea"></div>
   <span data-bind="text: formatCurrency(salesPrice)"></span>

   <script>
 /// <reference path="/Scripts/knockout-3.3.0.js"/>
       //The Model
       var data = {
           "Id": 123,
           "SalesPrice": 12500,
           "ListPrice": 16250,
           "ShortDesc": "Yamaha RD 350",
           "Description": "Yamaha RD 350 roadbike with helmet, jacket and gloves"
       };

       //The ViewModel
       var viewmodel = {
           id: ko.observable(data.id),
           salesPrice: ko.observable(data.SalesPrice),
           listPrice: ko.observable(data.ListPrice),
           shortDesc: ko.observable(data.ShortDesc),
           description: ko.observable(data.Description),
           formatCurrency: function (value) {
               return "R " + value().toFixed(2);
           }
       };

       //Bind the Viewmodel
       ko.applyBindings(viewmodel);
   </script>

</body>
</html>

No comments:

Post a Comment