【问题标题】:Knockout.js mapping from js and template usage来自 js 和模板使用的 Knockout.js 映射
【发布时间】:2016-06-26 15:02:39
【问题描述】:

主要概念如下 - 我们有包含部分的主要状态对象,每个部分都有自己的数据和类型。我想根据部分类型显示每个部分数据。主要对象如下所示:

var data = {
  state: {
    sections: [{
      section: {
        Id: "1",
        Type: "Text",
        Version: 2,
        Data: ["one", "two"]
      }
    }, {
      section: {
        Id: "2",
        Type: "Text",
        Version: 1,
        Data: ["one", "two"]
      }
    }]
  }
};

我正在尝试使用每个部分类型的剔除映射和模板来做到这一点,但我真的不知道如何做到这一点。我所拥有的就是这个 - https://jsfiddle.net/7hd8zed5/1/ 。任何建议如何做到这一点?

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    您可以通过提供一个方法来动态选择模板的名称,该方法采用foreach 循环的当前项并返回模板名称字符串。 (official documentation)

    以下是代码中“模板提供程序方法”的示例:

    更新数据绑定

    <ul data-bind="template: { name: getTemplateForSection, foreach: sections, as: 'obj' }"></ul>
    

    更新状态模型:

    function StateModel(data) {
      ko.mapping.fromJS(data, mapping, this);
    
      this.getTemplateForSection = function(sectionModel) {
        var section = sectionModel.section;
    
        switch (section.Type()) {
          case "Text":
            return "Text-template";
          default:
            return "Error-template";
        }
      }
    };
    

    我已经分叉了你的小提琴并包含了我提出的示例here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2012-04-05
      • 2012-12-05
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多