Knockout Max 103
by Barry Carter
HTML
<div class='liveExample'>
<h2>Hello, <span data-bind='text: always'> </span>!</h2>
<button data-bind="click: a_clicked">a</button>
<button data-bind="click: b_clicked">b</button>
<button data-bind="click: c_clicked">c</button>
</div>
</div>
<div data-bind="text: a">
</div>
<div data-bind="text: b">
</div>
<div data-bind="text: c">
</div>
<div data-bind="foreach: testElements">
<div>
</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.a = ko.observable("a");
this.b = ko.observable("b");
this.c = ko.observable("c");
this.testElements = ko.observableArray(["one", "two", "three"]);
this.always = ko.computed(function() {
// I look at any observable and change if any of those change
if (false) {
// not observed
self.b();
}
// is observed!
self.c();
console.log("I Triggered!");
return self.a();
});
this.a_clicked = function() {
self.a(self.a() + "1");
}
this.b_clicked = function() {
self.b(self.b() + "1");
}
this.c_clicked = function() {
self.c(self.c() + "1");
}
// lets watch variable a for changes
var myAppSubscription = self.a.subscribe(function(newVal) {
console.log("New Value for sub is: " + newVal);
});
// lets watch a different one and throttle
this.throttled = ko.computed(function() {
console.log("New Value for B is: " + self.b());
return self.b();
}).extend({ rateLimit: 3000 });
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work