Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference typescript's enum value from knockout data-bind?

I'm trying to make this work (page complains about CustomerExperience being undefined):

<div data-bind="visible: $data.customerExperienceObservable() === CustomerExperience.Loading">
    Loading...
</div>

where CustomerExperience is defined in TypeScript:

export enum CustomerExperience {
    Loading = 1,
    Unconfigured = 2,
    Data = 3
}

transpiled to:

(function (CustomerExperience) {
    CustomerExperience[CustomerExperience["Loading"] = 1] = "Loading";
    CustomerExperience[CustomerExperience["Unconfigured"] = 2] = "Unconfigured";
    CustomerExperience[CustomerExperience["Data"] = 3] = "Data";
})(exports.CustomerExperience || (exports.CustomerExperience = {}));
var CustomerExperience = exports.CustomerExperience;

with context applied to an instance of one class:

ko.applyBindings(dataProvider);

I understand that I can make it work if I define CustomerExperience as a property of bound dataProvider. But I'm trying to understand whether how to do it with TypeScript enum.

Any ideas? :)

PS: For now I used === 1 to make it work.

like image 308
ZakiMa Avatar asked May 20 '26 09:05

ZakiMa


1 Answers

Ended up with this solution (thank you Carrie Kendall!):

public customerExperienceLoading: KnockoutComputed<boolean> = ko.computed({
    owner: this,
    read:  () => {
        return this.customerExperienceObservable() === CustomerExperience.Loading; } });

And bound it as regular boolean:

data-bind="visible: $data.customerExperienceLoading() === true"
like image 139
ZakiMa Avatar answered May 22 '26 02:05

ZakiMa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!