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...
DESIRED
This is a modification of Jeff's answer, with the binding context preserved
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 };
}
};
Now apply with parent and root: