ZakiMa ZakiMa - 3 months ago 10
TypeScript Question

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.

Answer

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"
Comments