Thursday, 10 September 2015

Another Knockout example and a lesson learnt

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


1. Add the following Knockout code in the <script> tag in the header
<script>
/// <reference path="/Scripts/knockout-3.3.0.js"/>
   function AppViewModel() {
       this.firstName = ko.observable();
       this.lastName = ko.observable();
       this.msg = ko.observable();
           
       this.writeMsg = function () {
           var p1 = this.firstName() + " " + this.lastName();
           this.msg("Hello " + p1);
       };
   }
   // Activates knockout.js
   ko.applyBindings(new AppViewModel());
</script>


2. Add the following html code in the body of the document
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<button data-bind="click: writeMsg">Show</button>
<p data-bind="text: msg"></p>


3. Save your document and right-click the background of the document and select View in Browser
4. You are getting an error:”Error: Unable to get property ‘nodeType’ of undefined or null reference” - a lesson learnt
5. The reason is that the Knockout code is trying to execute before the objects in the document has been initialised
6. To fix this, move the script block with the Knockout code to the bottom of the document, just before the closing </body> tag
7. Run the page again and it should work as expected
8. See the complete code below:


<!DOCTYPE html>
<html>
<head>
   <title>Knockout Example</title>
<meta charset="utf-8" />
   <script src="Scripts/knockout-3.3.0.js"></script>
</head>
<body>
   <p>First name: <input data-bind="value: firstName" /></p>
   <p>Last name: <input data-bind="value: lastName" /></p>
   <button data-bind="click: writeMsg">Show</button>
   <p data-bind="text: msg"></p>


   <script>
   /// <reference path="/Scripts/knockout-3.3.0.js"/>
       function AppViewModel() {
           this.firstName = ko.observable();
           this.lastName = ko.observable();
           this.msg = ko.observable();
           this.writeMsg = function () {
               var p1 = this.firstName() + " " + this.lastName();
               this.msg("Hello " + p1);
           };
       }
       // Activates knockout.js
       ko.applyBindings(new AppViewModel());
   </script>
</body>

</html>

No comments:

Post a Comment