Knockout.js Simple Counter - Knockout-js Typing CST Test
Loading…
Knockout.js Simple Counter — Knockout-js Code
Basic counter with increment, decrement, reset, and theme toggle.
<div class="container" data-bind="css: isDark() ? 'dark-theme' : 'light-theme'">
<h2>Counter: <span data-bind="text: count"></span></h2>
<div>
<button data-bind="click: increment">+</button>
<button data-bind="click: decrement">-</button>
<button data-bind="click: reset">Reset</button>
</div>
<button data-bind="click: toggleTheme">Switch to <span data-bind="text: isDark() ? 'Light' : 'Dark'"></span> Theme</button>
</div>
<script>
function CounterViewModel() {
this.count = ko.observable(0);
this.isDark = ko.observable(false);
this.increment = () => { this.count(this.count() + 1); };
this.decrement = () => { this.count(this.count() - 1); };
this.reset = () => { this.count(0); };
this.toggleTheme = () => { this.isDark(!this.isDark()); };
}
ko.applyBindings(new CounterViewModel());
</script>
<style>
.dark-theme { background-color: #222; color: #eee; padding: 1em; }
.light-theme { background-color: #fff; color: #000; padding: 1em; }
button { margin: 0.25em; padding: 0.5em 1em; }
</style>Knockout-js Language Guide
Knockout.js is a lightweight JavaScript library that uses the MVVM (Model-View-ViewModel) pattern to create responsive, data-driven UIs with declarative bindings. It emphasizes simplicity, observables, and automatic UI updates.
Primary Use Cases
- ▸Data-driven dashboards
- ▸Forms with heavy user interaction
- ▸Enterprise legacy SPA systems
- ▸MVVM-style large UI logic
- ▸Low-dependency applications where frameworks like React/Vue are unnecessary
Notable Features
- ▸Observable variables and computed observables
- ▸Declarative two-way bindings
- ▸Automatic UI refresh
- ▸Dependency tracking engine
- ▸Templating and custom bindings
Origin & Creator
Created by Steve Sanderson at Microsoft in 2010 to simplify dynamic web UIs using the MVVM pattern.
Industrial Note
Knockout.js is still used in long-lived enterprise systems, internal dashboards, and large legacy codebases due to its stability, backward compatibility, and lightweight footprint.