嵌套对象中带有$ parent的Knockout问题

时间:2015-07-31 09:13:14

标签: javascript knockout.js

当父对象不在根级别时,我在访问视图模型中的父对象时遇到问题。

例如,以下作品(http://jsfiddle.net/rampmr/4r7zep25/

  <div>
    <!-- ko foreach: items -->

        <input type="checkbox" data-bind="checkedValue: $data, checked: $root.chosenItems" />
        <span data-bind="text:$data"></span> <br>

    <!-- /ko -->

    <!-- ko foreach: chosenItems -->
            Checked values are <span data-bind="text:$data"></span> <br>
    <!-- /ko -->
    </div>

    <script>

        $(function(){       

            function viewModel() {
                    var self = this;
                    self.items = ko.observableArray();
                    self.chosenItems= ko.observableArray()
                    self.items.push('Choice 1','Choice 2' );
                    self.chosenItems().push('Choice 1');
                        console.log(self);
                }
        var vm = new viewModel();
            ko.applyBindings(vm);

       });


    </script>

但是当我在View Model中有一个对象并且该对象有一个数组时,我在迭代数组时无法使用$ parent到达该对象(http://jsfiddle.net/rampmr/4nsjn948/4/

<DIV>

<!-- ko foreach: customValues.avblFruits -->
    <input type="checkbox" data-bind="checkedValue: $data, checked: $parent.Fruits" />
    <span data-bind="text: $data"></span>
<!-- /ko -->

</DIV>

<br>

<DIV>

<!-- ko foreach: customValues.Fruits -->    
    Selected Values are <span data-bind="text: $data"></span> <br>
<!-- /ko -->

</DIV>

<script>

    $(function(){       

        var selectedValues = {"Fruits" : ['Apple']};

        var availableValues = {"avblFruits" : ['Apple', 'Orange']};

        function CustomValues(data){
                var self = this;
                ko.mapping.fromJS(data, {}, self);
                ko.mapping.fromJS(availableValues, {}, self);
                console.log(self);
        }

        var mapping = {
            create: function (options) {
                return new CustomValues(options.data);
            }
        };

        function viewModel() {
                var self = this;
                self.customValues = ko.mapping.fromJS(selectedValues, mapping );                            
                console.log(self);

            }
    var vm = new viewModel();
        ko.applyBindings(vm);
    }); 


</script>

当我改变

<input type="checkbox" data-bind="checkedValue: $data, checked: $parent.Fruits" /> 

<input type="checkbox" data-bind="checkedValue: $data, checked: $root.customValues.Fruits" />

为什么它不能与$ parent合作?

1 个答案:

答案 0 :(得分:1)

您正在尝试根据您的视图结构引用不存在的parent。尝试使用适合案例的with绑定,您可以分别使用$parent$root

查看:

<div data-bind="with:customValues"> //level 1 
<!-- ko foreach:avblFruits --> // level 2 i.e level 1 is parent of level 2
 <input type="checkbox" data-bind="checkedValue: $data, checked: $parent.Fruits" /> 
    <span data-bind="text: $data"></span>
<!-- /ko -->
</div>

工作样本 here