試圖獲得knockoutjs(2.21)介紹使用typescript(0.9)的教程。數據綁定似乎不起作用。這是我多年來看到的第一個JavaScript。我想我錯過了如何正確地將html連接到使用typescript類生成的viewmodel。只有在我嘗試將該類引入該教程時纔會出現問題。這是一個jsfiddle。Typescript knockoutjs數據綁定不起作用
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());
};
http://meta.stackexchange.com/questions/147616/what-do-you-mean-it-doesnt-work –
對不起,我應該說數據綁定不起作用的標題。 – javelinBCD