Knockout JS with Mappings递归模板

时间:2015-06-17 15:47:38

标签: javascript ajax knockout.js knockout-mapping-plugin

我正在使用带有映射插件的knockout JS:

https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output

似乎我无法访问数据。

这是一个纯粹的淘汰赛和纯JSON的工作示例:

http://jsfiddle.net/u0hv6wxe/2/

这是一个破解的例子,其中挖空和映射没有呈现任何内容:

http://jsfiddle.net/95zztzkq/1/

我使用映射的原因是为了防止创建一个包含来自ajax的数千个属性的模型。

插件上的文档:

http://knockoutjs.com/documentation/plugins-mapping.html

JS:

var initialData = {
    '@type': 'type1',
    'contents': [
        {
            '@type' : 'type2',
            'stringx': 'test'
        },
        {
            '@type' : 'type2',
            'stringx': 'test2'
        }
    ]
};
defaultData = ko.mapping.fromJS(initialData);
ko.applyBindings(defaultData);
console.log(defaultData['@type']());
console.log(defaultData.contents()[0]['@type']());
console.log(defaultData.contents()[1]['@type']());

模板:

<!-- ko template: { name: 'mainTemplate', data: $data } --><!-- /ko -->

<script id="mainTemplate" type="text/html">
    <!-- ko if: ($data['@type']=='type1') -->
            <div class="Page">
                PageTest
            <!-- ko if: ($data.contents) -->
                    <!-- ko template: { name: 'mainTemplate', foreach: $data.contents } -->
                    <!-- /ko -->
            <!-- /ko -->
            </div>
    <!-- /ko -->    
    <!-- ko if: ($data['@type']=='type2') -->
            <div class="test">
                StringTest <span data-bind="text: stringx"></span>
            </div>
    <!-- /ko -->    
</script>

我在这个问题上被困了2天,非常感谢所有的帮助!

谢谢:)

1 个答案:

答案 0 :(得分:1)

在检查视图中的条件时,我们需要使用()来读取可观察的值,这将解决问题

查看:

<!-- ko template: { name: 'mainTemplate', data: $data } --><!-- /ko -->

<script id="mainTemplate" type="text/html">
    <!-- ko if: ($data['@type']()=='type1') -->
            <div class="Page">
                PageTest
            <!-- ko if: ($data.contents) -->
                    <!-- ko template: { name: 'mainTemplate', foreach: $data.contents } -->
                    <!-- /ko -->
            <!-- /ko -->
            </div>
    <!-- /ko -->    
    <!-- ko if: ($data['@type']()=='type2') -->
            <div class="test">
                StringTest <span data-bind="text: stringx"></span>
            </div>
    <!-- /ko -->    
</script>

工作小提琴 here