Yeah, in many of my projects I use TypeScript for my KO viewmodels.
The following TypeScript:
class MyViewModel {
MyObservable = ko.observable();
MyComputed = ko.computed(() => {
return this.MyObservable() * 2;
})
}
Renders the following valid viewmodel:
var MyViewModel = (function () {
function MyViewModel() {
var _this = this;
this.MyObservable = ko.observable();
this.MyComputed = ko.computed(function () {
return _this.MyObservable() * 2;
});
}
return MyViewModel;
})();
Be careful when using functions though; the following TypeScript function:
MyFunction() {
if (this.MyComputed() > 4) {
alert('Higher than 4');
}
}
Will render:
MyViewModel.prototype.MyFunction = function () {
if (this.MyComputed() > 4) {
alert('Higher than 4');
}
};
Meaning you might run into scope problems with this when you're using this function directly in your binding for example (data-bind="click: MyFunction" would fail).
To prevent these scope issues, you should be declaring the functions in your viewmodels as lambas:
MyFunction = () => {
if (this.MyComputed() > 4) {
alert('Higher than 4');
}
}
Renders:
this.MyFunction = function () {
if (_this.MyComputed() > 4) {
alert('Higher than 4');
}
};