3

我使用以下代码在 knockout.js 中创建了具有多级数据的树。

<ul data-bind="template: { name: 'itemTmpl', foreach: $data.items }"></ul>

<script id="itemTmpl" type="text/html">
    <li>
        <span data-bind="text: name"></span>
        <input type='checkbox'>
        <ul data-bind="template: { name: 'itemTmpl', foreach: $data.items }">

        </ul>
    </li>
</script>

但是现在我想以这种方式在淘汰赛中扩展它,如果我检查了父级,那么它的所有子级都被选中,如果取消选中父级子级则未被选中。

Here is js fiddle link

http://jsfiddle.net/tEGUp/

4

1 回答 1

1

I made a version that does not alter the orginal data but uses KO mapping.

I also took the opertunity to show how much less code you need to write with my Convention library

MyApp.TreeViewModel = function(data) {
    var mapping = {
        items: {
            create: function(options) {
                return new MyApp.TreeViewModel(options.data);
            }
        }
    };
    this.checked = ko.observable(false); 
    this.checked.subscribe(this.onChecked, this);

    this.items = ko.observableArray();

    ko.mapping.fromJS(data, mapping, this);     
};

MyApp.TreeViewModel.prototype = {
    constructor: MyApp.TreeViewModel,
    onChecked: function(checked) {
        ko.utils.arrayForEach(this.items(), function(item) {
            item.checked(checked);
        });
    }
};
于 2013-09-28T15:16:03.463 回答