【问题标题】:knockout depandent variables: how to define structure properly淘汰因变量:如何正确定义结构
【发布时间】:2013-11-26 09:41:17
【问题描述】:

我是 Knockout 的新手,我有以下问题:

我有来自数据库的 Id,每个 Id 都有其对应的描述(这实际上是 .NET 中的枚举,但我认为这在这个问题中并不重要)。

例如,

a) 对于变量“PType”:0 - Undefined; 1 - Low Structure; 2 - Hight Structure b) 对于变量“ClientType”:0 - Undefined, 1 - P Type; 2 - S Type 等其他一些变量也

如何正确定义此依赖项的模型? 目前我只有类似的ID

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

我在页面上显示 ID:

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

但是,我需要有类似的东西:PTypeDescriptionClientTypeDescription 才能显示给用户。我相信这些在某种程度上是因变量,但不能让它发挥作用。

【问题讨论】:

    标签: javascript knockout.js


    【解决方案1】:

    首先我假设你已经知道你有什么枚举,当你通过 AJAX 获取数据时,你得到的枚举值表示为 integer 而不是 string

    您可以轻松地在 Javascript 中模拟枚举(检查 this article):

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

    所以,你的视图模型可以是这样的:

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

    要将您的枚举表示为枚举,您需要编写调用函数,该函数采用 value("your enum key") 和要使用的枚举("you can use inline function for that")。

    JsFiddle Demo

    更新
    检查这个SO answer 到另一个 JS 中枚举的实现,它简单有效

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2013-02-19
      • 1970-01-01
      • 2017-10-28
      • 2014-05-06
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多