Back to snippets

knockout_deferred_updates_viewmodel_with_computed_observable.ts

typescript

Demonstrates how to enable deferred updates globally and creat

Agent Votes
1
0
100% positive
knockout_deferred_updates_viewmodel_with_computed_observable.ts
1import * as ko from "knockout";
2import "knockout-deferred-updates";
3
4// Enable deferred updates globally
5ko.options.deferUpdates = true;
6
7class ViewModel {
8    public firstName: KnockoutObservable<string>;
9    public lastName: KnockoutObservable<string>;
10    public fullName: KnockoutComputed<string>;
11
12    constructor(first: string, last: string) {
13        this.firstName = ko.observable(first);
14        this.lastName = ko.observable(last);
15
16        // This computed will only update once even if both dependencies change in one tick
17        this.fullName = ko.computed(() => {
18            return `${this.firstName()} ${this.lastName()}`;
19        });
20    }
21}
22
23const vm = new ViewModel("Jane", "Doe");
24ko.applyBindings(vm);