我想使用类似于Knockout foreach构造的东西来迭代对象的属性。这就是我想要创造的......
期望的结果
<table>
<tr>
<td>Name 1</td>
<td>8/5/2012</td>
</tr>
<tr>
<td>Name 2</td>
<td>2/8/2013</td>
</tr>
</table>
但是,我的模型看起来像这样......
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本身就是一个对象。此模板不起作用,但我如何更改它以生成上面所需的表?
编辑:此示例中的props
为name
和lastLogin
,但我需要一个与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>
答案 0 :(得分:62)
在现代浏览器中(或使用适当的polyfill),您可以迭代Object.keys(obj)
(该方法仅返回自己的可枚举属性,这意味着不需要额外的{{ 1}}检查):
hasOwnProperty
NB:我只是很好奇,看看这是否有效,上面的模板体比我想要在生产中使用的更污染(或者回到几个月之后,就像“wtf”)。
自定义绑定是一个更好的选择,我个人的偏好虽然是使用计算的observable或writeable computed observable(后者在使用<table>
<tbody data-bind="foreach: {data: data, as: '_data'}">
<tr data-bind="foreach: {data: Object.keys(props), as: '_propkey'}">
<th data-bind="text: _propkey"></th>
<td data-bind="text: _data.props[_propkey]"></td>
</tr>
</tbody>
</table>
响应时很方便a-la restful api)
答案 1 :(得分:46)
您总是可以创建一个绑定处理程序来处理转换。
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>
答案 2 :(得分:21)
这是Jeff的答案的修改,保留了绑定上下文
ko.bindingHandlers.eachProp = {
transformObject: function (obj) {
var properties = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
properties.push({ key: key, value: obj[key] });
}
}
return ko.observableArray(properties);
},
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor()),
properties = ko.bindingHandlers.eachProp.transformObject(value);
ko.bindingHandlers['foreach'].init(element, properties, allBindingsAccessor, viewModel, bindingContext)
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var value = ko.utils.unwrapObservable(valueAccessor()),
properties = ko.bindingHandlers.eachProp.transformObject(value);
ko.bindingHandlers['foreach'].update(element, properties, allBindingsAccessor, viewModel, bindingContext)
return { controlsDescendantBindings: true };
}
};
现在适用于父和根:
<table>
<tbody data-bind="foreach: data">
<tr data-bind="eachProp: props">
<td data-bind="text: value, click: $root.doSomething"></td>
</tr>
</tbody>
</table>
答案 3 :(得分:2)
<table>
<tr data-bind="foreach: {data: data, as: 'item'}">
<td data-bind="foreach: { data: Object.keys(item), as: 'key' }">
<b data-bind="text: item[key]"></b>
</td>
</tr>
</table>
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);
希望这有帮助(原谅简洁)
<强>附录强>
这是一个正在测试的工作示例...
<table class="table table-hover">
<thead>
<tr>
<!-- ko foreach: gridOptions.columnDefs -->
<th data-bind="text: displayName"></th>
<!-- /ko -->
</tr>
</thead>
<tbody>
<!-- ko foreach: {data: gridOptions.data, as: 'item'} -->
<tr>
<!-- ko foreach: {data: Object.keys(item), as: 'key'} -->
<td>
<span data-bind="text: item[key]"></span>
</td>
<!-- /ko -->
</tr>
<!-- /ko -->
</tbody>
</table>
答案 4 :(得分:2)
据推测,存在一个更深层次的问题(see this thread at Google groups),即foreach将对象视为参数字典,而不是迭代的集合。
到目前为止,我的最佳解决方案是将foreach
和Object.keys(myobject)
中的unittest.loadTestsFromModule
合并为&#39;绑定上下文。
答案 5 :(得分:2)
使用任何基本对象的简化答案,为我工作:
<!-- ko foreach: {data: Object.keys(myObj)} -->
<span data-bind="text: $data"></span>
<span data-bind="text: $parent.myObj[$data]"></span>
<!-- /ko -->
答案 6 :(得分:0)
(不严格迭代属性,但确实创建上面的表格)
<div data-bind="template: { name: 'template', data: $data }"></div>
<script type="text/html" id="template">
<table data-bind="foreach: data()">
<tr>
<td data-bind="text: props.name"></td>
<td data-bind="text: props.lastLogin"></td>
</tr>
</table>
</script>
答案 7 :(得分:0)
我有点迟了,但我觉得这应该有用,一个简单的解决方案,不使用任何模板。
var json = [
{
"PortfolioCompanyId":240,
"dt":"2018-12-31 00:00:00.0",
"ValuationDate":"2017-09-30 00:00:00.0",
"capitalexpenditure":-5555660.0,
"workingcapitalchange":-812350.0
},
{
"PortfolioCompanyId":240,
"dt":"2019-12-31 00:00:00.0",
"ValuationDate":"2017-09-30 00:00:00.0",
"capitalexpenditure":-5613520.0,
"workingcapitalchange":-893530.0
},
{
"PortfolioCompanyId":240,
"dt":"2020-12-31 00:00:00.0",
"ValuationDate":"2017-09-30 00:00:00.0",
"capitalexpenditure":-5674130.0,
"workingcapitalchange":-982850.0
},
{
"PortfolioCompanyId":240,
"dt":"2021-12-31 00:00:00.0",
"ValuationDate":"2017-09-30 00:00:00.0",
"capitalexpenditure":-6241543.0,
"workingcapitalchange":-1081135.0
},
{
"PortfolioCompanyId":240,
"dt":"2022-12-31 00:00:00.0",
"ValuationDate":"2017-09-30 00:00:00.0",
"capitalexpenditure":-6865697.3,
"workingcapitalchange":-1189248.5
}
];
var DataModel = function () {
this.jsonArray = ko.observable(json);
};
ko.applyBindings(new DataModel());
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table" data-bind="foreach:jsonArray">
<tr data-bind="foreach:Object.keys($data)"> <!-- JSON Object -->
<td data-bind="text : $parent[$data]"></td>
</tr>
</table>