I am new to typescript and would like to combine it with the goodness of knockout. I have a computed observable, which currently works, but want to know is this the right way about it or is there a better way.
I am using the knockout definition file from nu-get. In it there are 4 KnockoutComputed(x) definitions.
I like the {} method of declaring observable's and would like to keep this. So long story short is this the correct method of declaring observables or is there an alternate way (maybe with intlisense in the function)
I am using the first like so:
class PersonViewModel {
public firstname: KnockoutObservable<string>;
public lastname: KnockoutObservable<string>;
public fullname: KnockoutComputed<string>;
constructor() {
this.firstname = ko.observable('');
this.lastname = ko.observable('');
this.fullname = ko.computed({
owner: this,
read: function () {
return this.firstname() + " " + this.lastname();
}
});
}
}
with the html snippet of:
<h2>Type Script and Knockout.</h2>
<input data-bind="value: firstname" />
<input data-bind="value: lastname" />
<div data-bind="text: fullname"></div>
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
Master KnockoutJS : Knockout JS - JavaScript MVVM Computed Observable is a function which is dependent on one or more Observables and automatically updates whenever its underlying Observables (dependencies) change.
In some scenarios, it is useful to programmatically determine if you are dealing with a computed observable. Knockout provides a utility function, ko. isComputed to help with this situation. For example, you might want to exclude computed observables from data that you are sending back to the server.
December 14, 2019 | TypeScript, Knockout. Knockout is a minimalist, mature and proven library for creating web applications. It isn't as feature rich as some of the more modern libraries & frameworks but it does what it does well, primarily being binding HTML elements against a data model.
Recommendation is to use arrow functions for computed. It will give you the desired intellisence as well:
this.fullname = ko.computed({
owner: this,
read: () => {
return this.firstname() + " " + this.lastname();
}
});
Basically that captures this
using closure so it doesn't matter who calls back the function. this
will continue to mean PersonViewModel
instead of any
. More : http://basarat.github.io/TypeScriptDeepDive/#/this
Try the intellisense in TypeScript Playground. You should get intellisense when you press this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With