尝试这样的事情:
<ul data-bind="keyvalue: properties">
<li>
<span data-bind="text: key"></span> :
<span data-bind="text: value"></span>
</li>
</ul>
对于 JavaScript:
function AppViewModel() {
this.properties = { b: 'c', d: 'e' };
}
ko.bindingHandlers['keyvalue'] = {
makeTemplateValueAccessor: function(valueAccessor) {
return function() {
var values = valueAccessor();
var array = [];
for (var key in values)
array.push({key: key, value: values[key]});
return array;
};
},
'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['foreach']['init'](element, ko.bindingHandlers['keyvalue'].makeTemplateValueAccessor(valueAccessor));
},
'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
return ko.bindingHandlers['foreach']['update'](element, ko.bindingHandlers['keyvalue'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
}
};
ko.applyBindings(new AppViewModel());