@arnoldo.moen
To implement a TypeScript class with a property as a class in Knockout.js, you can follow these steps:
1 2 3 4 5 6 7 8 9 |
class Person {
name: KnockoutObservable<string>;
age: KnockoutObservable<number>;
constructor(name: string, age: number) {
this.name = ko.observable(name);
this.age = ko.observable(age);
}
}
|
1 2 3 4 5 6 7 8 |
class ViewModel {
person: Person;
constructor() {
this.person = new Person("John Doe", 30);
ko.applyBindings(this);
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Knockout.js with TypeScript</title>
</head>
<body>
<h1>Hello, <span data-bind="text: person.name"></span>!</h1>
<p>You are <span data-bind="text: person.age"></span> years old.</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js"></script>
<script src="your-typescript-file.js"></script>
</body>
</html>
|
Make sure to compile your TypeScript code to JavaScript before running it in the browser. You can do this with a TypeScript compiler like tsc, or by setting up a build process in your IDE or build tool.