Knockout Max 101

by Barry Carter

HTML

<div class='liveExample'>   
    <p>First name: <input data-bind='value: firstName' /></p> 
    <p>Last name: <input data-bind='value: lastName' /></p> 
    <h2>Hello, <span data-bind='text: always'> </span>!</h2>  
</div>

<div data-bind="foreach: testElements">
  <div>
  I'm element <span data-bind="text: $root.computedPerElement($data)"></span>
  </div>
</div>

CSS

body { font-family: arial; font-size: 14px; }
.liveExample { padding: 1em; background-color: #EEEEDD; border: 1px solid #CCC; max-width: 655px; }
.liveExample input { font-family: Arial; }
.liveExample b { font-weight: bold; }
.liveExample p { margin-top: 0.9em; margin-bottom: 0.9em; }
.liveExample select[multiple] { width: 100%; height: 8em; }
.liveExample h2 { margin-top: 0.4em; font-weight: bold; font-size: 1.2em; }

JavaScript

// Here's my data model
var ViewModel = function(first, last) {
	var self = this;
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
 	  this.testElements = ko.observableArray(["one", "two", "three"]);
    
    this.always = ko.computed(function() {
        // I look at any observable and change if any of those change
        return self.firstName() + " " + self.lastName();
    });
    
    this.sometimes = ko.pureComputed(function() {
    	console.log("I computed pre!");
      
      return "Computed Pure";
    });
    
    this.computedPerElement = function(elementName) {
    	return ko.pureComputed(function() {
      	return "A am purely computed for element " + elementName; 
    	});
    };
};
 
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work