September 13, 2013

KnockOut.js - Hello World - basic html page

I recently discovered the fantastic knockout.js for my SharePoint UI development. The site has an amazing advanced live tutorial and live "Hello World" examples but it seems they forgot the basics: where is my simple HTML page Hello World code to cut-n-paste?! I wrote my own and put it here to help out the on-line community.

This code has all the basics you need to know to read, add and update to single properties and properties inside nested data.

<script type='text/javascript' src='knockout-2.3.0.js'></script>
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Knockout.js - Hello World - Basic Add and Update</title>
<script  >

function Model(){

$(document).ready(function () 
function Person(firstName,lastName) {
<body >
<body >

 //basic bindable property - will update UI when greeting("foo") is called.

 this.greeting = ko.observable("Hello World");
 //bindable array 
 this.items = ko.observableArray(["lamp", "rug", "table"]);
 //bindable array with bindable object properties
 this.people = ko.observableArray([new Person("John","Smith"),new Person("Bob","Smith")]);


 var model = new Model();




  //add a new string to the array

   //replace the string of the first item in the array

  model.items.replace(model.items()[0], "paper");

   //add a new person object

  model.people.push(new Person("Mark","Jones"));


  //replace the first name of the first row


  //replace a whole person object with another 
  model.people.replace(model.people()[1], new Person("Peter","Man"));

        this.firstName = ko.observable(firstName);

        this.lastName = ko.observable(lastName);

    <p data-bind="text: greeting"></p>

    <p><button id="greetingButton">Update</button> </p>


 <table border="1" >
        <tbody data-bind="foreach: items">
        <tr >
            <td data-bind="text: $data" ></td>
    <p><button id="itemsButtonAdd">Add</button> <button id="itemsButtonUpdate">Update</button></p>
 <table border="1" data-bind="with: people">
     <thead><tr><th>First Name</th><th>Last Name</th></tr></thead>
        <tbody data-bind="foreach: $data">
        <tr >
            <td data-bind="text: firstName" ></td>
            <td data-bind="text: lastName"></td>

No comments:

Post a Comment