renathy
renathy

Reputation: 5355

knockout depandent variables: how to define structure properly

I am new to Knockout, and I have the following question:

I have Ids coming from database and each Id has its corresponding Description (this is actualy enum in .NET, but I do not think this is important in this question).

For example,

a) for variable "PType": 0 - Undefined; 1 - Low Structure; 2 - Hight Structure b) for variable "ClientType": 0 - Undefined, 1 - P Type; 2 - S Type etc. for some other variables also

How to properly define model for this dependency? Currently I have only Ids like

PType: ko.observable();
ClientType: ko.observable();

and I show Ids on page:

<span data-bind="text: PType"></span>
<span data-bind="text: ClientType"></span>

However, I need to have something like: PTypeDescription and ClientTypeDescription to show for User. I believe that those are somehow dependant variables, but cannot get it working.

Upvotes: 1

Views: 154

Answers (1)

ebram khalil
ebram khalil

Reputation: 8331

First i 'll suppose that you already know what enums you have and when you get data via AJAX, you get enums value represented as integer not string

You can simulate enums in Javascript easily (check this article):

var PType = { 0: "Undefined", 1: "Low Structure", 2: "Hight Structure" }
var ClientType = { 0: "Undefined", 1: "P Type", 2: "S Type" }

So, your view-model can be something like:

var itemObj = {
    PType: ko.observable(0);
    ClientType: ko.observable(0);
    property1:ko.observable('')// put here the other properties if you have more
}

To get your enum represnted as enum you write call function that takes the value("your enum key") and which enum to use("you can use inline function for that").

JsFiddle Demo

Update
Check this SO answer to another implementaion for Enums in JS, it's simple and effective

Upvotes: 1

Related Questions