淘汰赛JS树形与复选框(Knockout JS treeview with checkboxes)

2019-09-29 20:32发布

我在我的淘汰赛应用模块,我想有复选框树型结构。 我试图实现与是以下

  • 如果我选择的孩子在该节点的所有父母和祖父母被选中,但用不同的图标。 像这样的事情
  • 如果用户选择母公司所有的孩子都选择这样的

开始做我自己的插件之前,没有淘汰赛有什么与此类似,我可以作为一个基础使用和借鉴呢?

Answer 1:

我相信使用一些库挂接到DOM元素,如jstree是不错的办法。 恕我直言,最好是单独的数据模型及其在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"}
]));


文章来源: Knockout JS treeview with checkboxes