Knockout JS treeview with checkboxes

时间:2017-01-27 07:52:48

标签: jquery knockout.js treeview

我的淘汰应用程序中有一个模块,我想要一个带有复选框的树型结构。我想要实现的是以下

  • 如果我选择子节点,则该节点中的所有父节点和祖父节点都会被选中但具有不同的图标。像这样enter image description here
  • 如果用户选择了父级,则会选择其所有子级,如enter image description here

在开始制作我自己的插件之前,淘汰赛中是否有类似的内容,我可以将其用作基础并在此基础上构建?

1 个答案:

答案 0 :(得分:2)

我相信使用一些像jstree这样的DOM元素挂钩的库是不好的方法。恕我直言,最好将数据模型及其在htlm中的解释分开。

这里是示例:https://jsfiddle.net/gqyk1ssh/

ko.bindingHandlers.prop = {
    update: function(element,valueAccessor) {
        var props = ko.toJS(valueAccessor());
        for (prop in props){
            element[prop] = ko.unwrap(props[prop]);
        }
    }
}


function model(folders){
    this.folders = ko.observableArray(ko.utils.arrayMap(folders,function(folder){
        return new modelFolder(folder);
    }));
};


function modelFolder(folder,parent){
    this.name = ko.observable(folder.name);
    this.checked = ko.observable(folder.checked);
    this.parent = parent;

    this.folders = ko.observableArray(
        folder.folders ?
            ko.utils.arrayMap(folder.folders,function(folder){
                return new modelFolder(folder,this);
            }.bind(this))
            : null
    );

    this.checkedChildFolders = ko.pureComputed(function(){
        return ko.utils.arrayFilter(this.folders(),function(folder){
            return folder.checked() || folder.checkedAllChildFolders() || folder.checkedSomeChildFolders()
        });
    },this)

    this.checkedSomeChildFolders = ko.pureComputed(function(){
        return this.folders().length>0 && !this.checkedAllChildFolders() && this.checkedChildFolders().length > 0 
    },this);

    this.checkedAllChildFolders = ko.pureComputed(function(){
        return this.folders().length>0 && this.checkedChildFolders().length == this.folders().length
    },this)  
}

modelFolder.prototype.setCheck = function(check){
    this.checkParents(check);
    this.checkMeAndChildrens(check);
}

modelFolder.prototype.checkMeAndChildrens = function(check){
    this.checked(check);
    ko.utils.arrayForEach(this.folders(),function(folder){
        folder.checkMeAndChildrens(check);
    });
}   

modelFolder.prototype.checkParents = function(check){
    if(this.parent){
        this.parent.checked(check);
        this.parent.checkParents(check);
    }
}


ko.applyBindings(new model([
    {"name":"Lorem", "folders":[
        {"name":"Dolor","folders":[
            {"name":"Hello","folders":[
                {"name":"Lorem"},
                {"name":"Dolor","checked":true},
                {"name":"Sit amet"}
            ]},
            {"name":"Bye"},
        ]},
        {"name":"Sit amet"}
    ]},
    {"name":"Ipsum"}
]));