How to use knockout to iterate over an object (not array)

前端 未结 8 547
不知归路
不知归路 2020-12-04 23:31

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

8条回答
  •  北海茫月
    2020-12-05 00:35

    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:

提交回复
热议问题