本文介绍了如何使用淘汰赛迭代对象(不是数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我想使用类似于 Knockout foreach 构造的东西来迭代对象的属性.这是我正在尝试创建的内容...

I want to use something similar to the Knockout foreach construct to iterate over the properties of an object. Here is what I am trying to create...

想要的结果

<table>
    <tr>
        <td>Name 1</td>
        <td>8/5/2012</td>
    </tr>
    <tr>
        <td>Name 2</td>
        <td>2/8/2013</td>
    </tr>
</table>

然而,我的模型看起来像这样......

However, my model looks like this...

JS

function DataModel(){
    this.data = ko.observableArray([{
                        entityId: 1,
                        props: {
                            name: 'Name 1',
                            lastLogin: '8/5/2012'
                        }
                    },
                    {
                        entityId: 2,
                        props: {
                            name: 'Name 2',
                            lastLogin: '2/8/2013'
                        }
                    }]);
}

var dataModel = new DataModel();
ko.applyBindings(dataModel);

每一行都有一个 entityId 和 props,它本身就是一个对象.此模板不起作用,但我如何更改它以生成上面所需的表格?

Each row has an entityId and props which is an object itself. This template doesn't work, but how would I change it to generate the desired table above?

本示例中的 propsnamelastLogin,但我需要一个与 name 中包含的内容无关的解决方案代码>道具.

The props in this example are name and lastLogin, but I need a solution that is agnostic to what is contained inside props.

我也有这个FIDDLE.

HTML

<div data-bind="template: { name: 'template', data: $data }"></div>

<script type="text/html" id="template">
    <table>
        <tr data-bind="foreach: data()">
            <td data-bind="text: entityId"></td>
        </tr>
    </table>
</script>

推荐答案

您始终可以创建一个绑定处理程序来处理转换.

You could always create a binding handler to handle the transformation.

ko.bindingHandlers.foreachprop = {
  transformObject: function (obj) {
    var properties = [];
    ko.utils.objectForEach(obj, function (key, value) {
      properties.push({ key: key, value: value });
    });
    return properties;
  },
  init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
    var properties = ko.pureComputed(function () {
      var obj = ko.utils.unwrapObservable(valueAccessor());
      return ko.bindingHandlers.foreachprop.transformObject(obj);
    });
    ko.applyBindingsToNode(element, { foreach: properties }, bindingContext);
    return { controlsDescendantBindings: true };
  }
};

然后应用它:

<div data-bind="template: { name: 'template', data: $data }"></div>

<script type="text/html" id="template">
    <table>
        <tbody data-bind="foreach: data">
            <tr data-bind="foreachprop: props">
                <td data-bind="text: value"></td>
            </tr>
        </tbody>
    </table>
</script>

这篇关于如何使用淘汰赛迭代对象(不是数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:35