JavaScript MVVM library that makes it easier to create rich, responsive UIs with automatic UI synchronization through observable data binding
npx @tessl/cli install tessl/npm-knockout@3.5.00
# Knockout.js
1
2
Knockout.js is a JavaScript MVVM (Model-View-ViewModel) library that enables developers to create rich, desktop-like user interfaces with automatic UI synchronization through observable data binding. It provides a powerful and extensible set of declarative bindings that allow HTML elements to automatically stay in sync with underlying data models, eliminating the need for manual DOM manipulation.
3
4
## Package Information
5
6
- **Package Name**: knockout
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install knockout`
10
- **CDN**: `https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js`
11
12
## Core Imports
13
14
```javascript
15
// ES6 Module
16
import ko from "knockout";
17
```
18
19
```javascript
20
// CommonJS
21
const ko = require("knockout");
22
```
23
24
```html
25
<!-- Browser Global -->
26
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js"></script>
27
<!-- ko global variable is available -->
28
```
29
30
## Basic Usage
31
32
```javascript
33
import ko from "knockout";
34
35
// Create a view model with observables
36
function ViewModel() {
37
this.firstName = ko.observable("John");
38
this.lastName = ko.observable("Doe");
39
40
// Computed observable
41
this.fullName = ko.computed(() => {
42
return this.firstName() + " " + this.lastName();
43
});
44
45
// Observable array
46
this.items = ko.observableArray(["Item 1", "Item 2"]);
47
48
// Methods
49
this.addItem = () => {
50
this.items.push("New Item " + (this.items().length + 1));
51
};
52
}
53
54
// Apply bindings to connect view model to DOM
55
ko.applyBindings(new ViewModel());
56
```
57
58
```html
59
<!-- HTML with data-bind attributes -->
60
<div>
61
<p>First name: <strong data-bind="text: firstName"></strong></p>
62
<p>Last name: <strong data-bind="text: lastName"></strong></p>
63
<p>Full name: <strong data-bind="text: fullName"></strong></p>
64
65
<input data-bind="value: firstName" />
66
<input data-bind="value: lastName" />
67
68
<ul data-bind="foreach: items">
69
<li data-bind="text: $data"></li>
70
</ul>
71
72
<button data-bind="click: addItem">Add Item</button>
73
</div>
74
```
75
76
## Architecture
77
78
Knockout.js is built around several key concepts:
79
80
- **Observables**: Properties that notify subscribers when they change
81
- **Computed Observables**: Derived values that automatically update when their dependencies change
82
- **Observable Arrays**: Arrays that track additions, deletions, and reordering
83
- **Bindings**: Declarative connections between view model properties and DOM elements
84
- **Templates**: Reusable UI patterns with data binding support
85
- **Components**: Self-contained UI widgets with their own view models and templates
86
87
## Capabilities
88
89
### Observable System
90
91
Core reactive data binding system providing observable values, computed observables, and observable arrays for automatic UI synchronization.
92
93
```javascript { .api }
94
function observable<T>(initialValue?: T): Observable<T>;
95
function observableArray<T>(initialItems?: T[]): ObservableArray<T>;
96
function computed<T>(evaluator: () => T): Computed<T>;
97
function pureComputed<T>(evaluator: () => T): PureComputed<T>;
98
```
99
100
```typescript { .api }
101
interface Observable<T> {
102
(): T; // Read value
103
(value: T): any; // Write value
104
subscribe(callback: (newValue: T) => void): Subscription;
105
peek(): T; // Read without creating dependency
106
valueHasMutated(): void; // Manually notify of changes
107
valueWillMutate(): void; // Notify before changes
108
}
109
110
interface ObservableArray<T> extends Observable<T[]> {
111
push(...items: T[]): number;
112
pop(): T | undefined;
113
shift(): T | undefined;
114
unshift(...items: T[]): number;
115
remove(item: T): T[];
116
removeAll(): T[];
117
indexOf(item: T): number;
118
replace(oldItem: T, newItem: T): void;
119
}
120
121
interface Computed<T> extends Observable<T> {
122
dispose(): void;
123
isActive(): boolean;
124
getDependenciesCount(): number;
125
}
126
```
127
128
[Observable System](./observables.md)
129
130
### Data Binding System
131
132
Declarative binding system that connects view models to DOM elements with automatic synchronization and a rich set of built-in binding handlers.
133
134
```javascript { .api }
135
function applyBindings(viewModel: any, rootNode?: Node): void;
136
function applyBindingsToNode(node: Node, bindings: object, viewModel: any): void;
137
function contextFor(node: Node): BindingContext | undefined;
138
function dataFor(node: Node): any;
139
```
140
141
```typescript { .api }
142
interface BindingContext<T = any> {
143
$data: T;
144
$root: any;
145
$parent?: any;
146
$parents: any[];
147
$index?: Observable<number>;
148
$component?: any;
149
}
150
151
const bindingHandlers: {
152
// Text and appearance
153
text: BindingHandler;
154
html: BindingHandler;
155
visible: BindingHandler;
156
css: BindingHandler;
157
style: BindingHandler;
158
attr: BindingHandler;
159
class: BindingHandler;
160
161
// Control flow
162
foreach: BindingHandler;
163
if: BindingHandler;
164
ifnot: BindingHandler;
165
with: BindingHandler;
166
167
// Form fields
168
value: BindingHandler;
169
click: BindingHandler;
170
event: BindingHandler;
171
submit: BindingHandler;
172
enable: BindingHandler;
173
disable: BindingHandler;
174
checked: BindingHandler;
175
options: BindingHandler;
176
177
// Templates and components
178
template: BindingHandler;
179
component: BindingHandler;
180
};
181
```
182
183
[Data Binding](./binding.md)
184
185
### Utility Functions
186
187
Comprehensive utility library providing array manipulation, DOM utilities, data conversion, and cross-browser compatibility functions.
188
189
```javascript { .api }
190
const utils: {
191
// Array utilities
192
arrayForEach<T>(array: T[], action: (item: T, index: number) => void): void;
193
arrayFilter<T>(array: T[], predicate: (item: T) => boolean): T[];
194
arrayMap<T, U>(array: T[], mapping: (item: T) => U): U[];
195
arrayIndexOf<T>(array: T[], item: T): number;
196
197
// Object utilities
198
extend<T, U>(target: T, source: U): T & U;
199
objectForEach(obj: object, action: (key: string, value: any) => void): void;
200
201
// Observable utilities
202
unwrapObservable<T>(value: T | Observable<T>): T;
203
peekObservable<T>(value: T | Observable<T>): T;
204
205
// DOM utilities
206
parseHtmlFragment(html: string): Node[];
207
setHtml(node: Node, html: string): void;
208
triggerEvent(element: Element, eventType: string): void;
209
registerEventHandler(element: Element, eventType: string, handler: EventListener): void;
210
211
// Data utilities
212
parseJson(jsonString: string): any;
213
stringifyJson(data: any): string;
214
postJson(url: string, data: any): void;
215
};
216
```
217
218
[Utilities](./utils.md)
219
220
### Component System
221
222
Reusable UI component system with view model and template composition, registration, and loading capabilities for modular application architecture.
223
224
```javascript { .api }
225
const components: {
226
register(name: string, config: ComponentConfig): void;
227
unregister(name: string): void;
228
isRegistered(name: string): boolean;
229
get(name: string, callback: (definition: Component) => void): void;
230
clearCachedDefinition(name: string): void;
231
};
232
```
233
234
```typescript { .api }
235
interface ComponentConfig {
236
viewModel?: ViewModelConfig;
237
template: TemplateConfig;
238
synchronous?: boolean;
239
}
240
241
interface Component {
242
template: Node[];
243
createViewModel?: (params: any, componentInfo: ComponentInfo) => any;
244
}
245
246
interface ComponentInfo {
247
element: Node;
248
templateNodes: Node[];
249
}
250
```
251
252
[Components](./components.md)
253
254
### Template System
255
256
Flexible templating system supporting multiple template engines, template sources, and rendering options for dynamic content generation.
257
258
```javascript { .api }
259
function renderTemplate(
260
template: string | Node,
261
dataOrBindingContext?: any,
262
options?: TemplateOptions,
263
targetNode?: Node,
264
renderMode?: "replaceChildren" | "replaceNode" | "ignoreTargetNode"
265
): void;
266
267
function setTemplateEngine(templateEngine: TemplateEngine): void;
268
```
269
270
```typescript { .api }
271
interface TemplateOptions {
272
templateEngine?: TemplateEngine;
273
afterRender?: (elements: Node[], data: any) => void;
274
}
275
276
abstract class TemplateEngine {
277
abstract renderTemplateSource(
278
templateSource: TemplateSource,
279
bindingContext: BindingContext,
280
options: TemplateOptions
281
): Node[];
282
}
283
```
284
285
[Templates](./templates.md)
286
287
### Performance and Optimization
288
289
Task scheduling, memoization, and configuration options for controlling Knockout.js runtime behavior and optimizing performance.
290
291
```javascript { .api }
292
const tasks: {
293
scheduler: (callback: () => any) => void;
294
schedule(callback: () => any): number;
295
cancel(handle: number): void;
296
runEarly(): void;
297
};
298
299
const memoization: {
300
memoize(callback: (val: any) => void): Node[];
301
unmemoize(memoId: string, callbackParams: any[]): void;
302
unmemoizeDomNodeAndDescendants(domNode: Node, extraCallbackParamsArray: any[]): void;
303
parseMemoText(memoText: string): string;
304
};
305
```
306
307
[Performance and Optimization](./performance.md)
308
309
## Data Conversion Functions
310
311
```javascript { .api }
312
function toJS(viewModel: any): any;
313
function toJSON(viewModel: any, replacer?: Function, space?: string | number): string;
314
function unwrap<T>(value: T | Observable<T>): T;
315
```
316
317
## Testing Functions
318
319
```javascript { .api }
320
function isObservable(obj: any): boolean;
321
function isObservableArray(obj: any): boolean;
322
function isComputed(obj: any): boolean;
323
function isPureComputed(obj: any): boolean;
324
function isSubscribable(obj: any): boolean;
325
function isWriteableObservable(obj: any): boolean;
326
function isWritableObservable(obj: any): boolean;
327
```
328
329
## Error Handling
330
331
```javascript { .api }
332
/**
333
* Global error handler for Knockout.js errors
334
* @param error - Error object to handle
335
*/
336
function onError(error: Error): void;
337
```
338
339
## Configuration
340
341
```javascript { .api }
342
const options: {
343
deferUpdates: boolean; // Defer observable updates
344
useOnlyNativeEvents: boolean; // Use only native DOM events
345
foreachHidesDestroyed: boolean; // Hide destroyed items in foreach
346
createChildContextWithAs: boolean; // Create child context with 'as' binding
347
};
348
```
349
350
## Version Information
351
352
```javascript { .api }
353
const version: string;
354
```