简体   繁体   English

KnockoutJS和嵌套可排序列表(二维)

[英]KnockoutJS and Nested Sortable List (Two-Dimensional)

I am looking for a way to implement a simple nested/nestable tree structure in KnockoutJS; 我正在寻找一种在KnockoutJS中实现简单的嵌套/可嵌套树结构的方法; and it should only allow two levels. 并且只能允许两个级别。

What I found so far is this (and a range of very similar approaches here on SO): Knockout.js nested sortable bindings 到目前为止,我发现的是这个(以及SO上的一系列非常相似的方法): Knockout.js嵌套可排序绑定

However, in this example - and the others, "Containers" cannot become "Children" and vice versa. 但是,在此示例以及其他示例中,“容器”不能成为“孩子”,反之亦然。

Basically, I am looking for a structure like this: http://jsfiddle.net/uhVAW/2/ 基本上,我正在寻找这样的结构: http : //jsfiddle.net/uhVAW/2/

Ie it will ultimately render a list with two levels: parent categories and their children. 也就是说,它将最终呈现一个具有两个级别的列表:父类别和他们的子类别。

My tree-structure in the Knockout ViewModel takes this shape (without all the updating logic): 我在Knockout ViewModel中的树结构采用以下形状(没有所有更新逻辑):

 var VM = function(cats)
 {
    this.categories = ko.observableArray(cats); // bound to the list
 }

 var Category = function
 {
    this.name = ko.observable();
    this.children = ko.observableArray([]); // if exists (i.e. if the cat is a parent), this is bound to a list within the <li>
 }

So, in essence: 因此,本质上:

  1. Sorting parent level 排序父级
  2. Sorting children within parents 在父母中对孩子进行分类
  3. Children can become parents & vice versa 孩子可以成为父母,反之亦然
  4. Only allowing n-levels of nesting (2 in my case) 仅允许n层嵌套(本例中为2)

Cheers! 干杯!

Here is a simple tree view using knockout-sortable with recursive templates: http://jsfiddle.net/rniemeyer/Lqttf/ 这是一个简单的树形视图,它使用带有可递归模板的敲除排序http : //jsfiddle.net/rniemeyer/Lqttf/

The view model would just look like: 视图模型如下所示:

var TreeItem = function(name, children) {
   this.name = ko.observable(name);
   this.children = children && ko.observableArray(children);
};

ko.applyBindings({
    root: new TreeItem("root", [
       new TreeItem("A", [
          new TreeItem("A1"),
          new TreeItem("A2")
       ]),
       new TreeItem("B", [
          new TreeItem("B1"),
          new TreeItem("B2")
       ])
    ])
});

The view would look like: 该视图如下所示:

<script id="nodeTmpl" type="text/html">
    <li>
        <a href="#" data-bind="text: name"></a>
        <div data-bind="if: children">
           <ul data-bind="sortable: { template: 'nodeTmpl', data: $data.children }"></ul>            
        </div>
    </li>
</script>

<ul data-bind="template: { name: 'nodeTmpl', data: root }"></ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM