我有一个从building a treeview in aurelia
无耻获取的树形结构当我将节点推送到树上时,这非常有用。我想要做的是解析一个json对象并将其推送到树上。这部分工作,因为树被渲染,但我无法扩展/折叠有孩子的节点。我相信这是因为调用hasChildren是一个方法而不是属性,可能是深层绑定。我已经尝试将此方法更改为get属性,但似乎无法使其工作。
节点模型类
export class NodeModel {
public name: string;
public visible: boolean;
public children: NodeModel[];
public expanded: boolean;
public icon: string;
constructor(name: string, children: NodeModel[])
{
this.name = name;
this.children = children || [];
this.visible = true;
if (this.hasChildren()) {
this.icon = "fa fa-chevron-down";
this.expanded = true;
}
}
hasChildren(): boolean {
return this.children.length > 0;
}
toggleNode(): void {
for (var i: number = 0; i < this.children.length; i++) {
this.children[i].visible = !this.children[i].visible;
}
this.expanded = !this.expanded;
if (this.expanded === true) {
this.icon = "fa fa-chevron-down";
} else {
this.icon = "fa fa-chevron-right";
}
}
}
Treeview VM
import {NodeModel} from "node-model";
export class T {
private locations: NodeModel[];
constructor() {
this.locations = [];
var texas = new NodeModel('Texas',
[new NodeModel('Houston', []),
new NodeModel('Austin', [])]);
console.log(JSON.stringify(texas));
this.locations = [texas];
}
addCardiff(): void {
var cardiff = new NodeModel('Cardiff',
[new NodeModel('Cardiff Bay', [])]);
this.locations.push(cardiff);
}
addBristol(): void {
var bristol = `{"name":"Bristol","children":
[{"name":"Easton","children":[],"visible":true},
{"name":"Eastville","children":[],"visible":true}],
"visible":true,"icon":"fa fa-chevron-down","expanded":true}`;
var d = JSON.parse(bristol);
this.locations.push(d);
}
}
树节点组件
import {bindable} from 'aurelia-framework';
export class TreeNode {
@bindable current = null;
}
树节点组件视图
<template>
<ul show.bind="current.visible" style="list-style-type: none;">
<li>
<div>
<span if.bind="current.hasChildren()" click.trigger="current.toggleNode()" class="${current.icon}"></span>
<span>${current.name}</span>
</div>
<tree-node repeat.for="node of current.children" current.bind="node"></tree-node>
</li>
</ul>
</template>
查看
<template>
<require from="tree-node"></require>
<tree-node repeat.for="node of locations" current.bind="node"></tree-node>
<button click.trigger="addCardiff()" class="btn btn-default">Add Cardiff</button>
<button click.trigger="addBristol()" class="btn btn-default">Add Bristol</button>
</template>
以下的输出
非常感谢任何想法。
此致
麦克
答案 0 :(得分:1)
addBristol()
方法部分有效,因为您正在推送普通的javascript对象,而不是NodeModel
对象。在将对象及其子对象推送到NodeModel
数组之前,必须将其转换为locations
对象。这样,您就可以拨打hasChildren()
。