KnockoutJS Click Counter
by mrjordy
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div class='liveExample'>
<div><span data-bind='text: numberOfClicks'> </span> clicks</div>
<button data-bind='click: registerClick, disable: hasClickedTooManyTimes'>Clickable Area</button>
<div data-bind='visible: hasClickedTooManyTimes'>
You look like you're having trouble finding what you're looking for.
<button data-bind='click: resetClicks'>Search box resets clicks</button>
</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; }
JavaScript
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 30;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());