试图让 knockoutjs (2.21) 介绍教程与 typescript (0.9) 一起使用。数据绑定似乎不起作用。这是我多年来看到的第一个 javascript。我想我错过了如何正确地将 html 连接到使用打字稿类生成的视图模型。仅在我尝试将课程介绍给教程时才出现问题。这是一个jsfiddle。
HTML片段:
<body>
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
<button data-bind="click: capitalizeLastName">Go Caps</button>
</body>
打字稿片段
class koIntroductionViewModel {
firstName: any;
lastName: any;
fullName: any;
constructor() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(this.createFullname());
}
createFullname() {
return this.firstName + " " + this.lastName;
}
capitalizeLastName() {
var currentVal = this.lastName;
this.lastName = currentVal.toUpperCase();
}
}
window.onload = () => {
ko.applyBindings(new koIntroductionViewModel());
}
生成的 javascript
var koIntroductionViewModel = (function () {
function koIntroductionViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(this.createFullname());
}
koIntroductionViewModel.prototype.createFullname = function () {
return this.firstName + " " + this.lastName;
};
koIntroductionViewModel.prototype.capitalizeLastName = function () {
var currentVal = this.lastName;
this.lastName = currentVal.toUpperCase();
};
return koIntroductionViewModel;
})();
window.onload = function () {
// Activates knockout.js
ko.applyBindings(new koIntroductionViewModel());
};