2016-11-25 32 views
2

是否有可能以編程方式在aurelia中創建組件,然後以某種方式將其綁定到視圖中該類型的標記。例如,像簡單的樹形視圖,請參閱下面的HTML模板中的註釋。以編程方式實例化Aurelia中的組件


樹view.ts

import {TreeNode} from "./tree-node"; 

export class TreeView<T> { 
    private _rootNodes: TreeNode<T>[] = []; 

    get rootNodes(): TreeNode<T>[] { 
     return this._rootNodes; 
    } 

    public addRootNode(node: TreeNode<T>) { 
     this._rootNodes.push(node); 
    } 
} 

樹node.ts

export class TreeNode<T> { 

    private _value: T; 
    private _name: string; 
    private _children: TreeNode<T>[] = []; 

    get value(): T { 
     return this._value; 
    } 

    get name(): string { 
     return this._name; 
    } 

    get children(): TreeNode<T>[] { 
     return this._children; 
    } 

    public addChild(child: TreeNode<T>): void { 
     this._children.push(child); 
    } 

    constructor(name: string, value: T) { 
     this._name = name; 
     this._value = value; 
    } 
} 

樹view.html

<template> 
    <!-- Something like this is the intend --> 
    <tree-node repeat.for="node of rootNodes"></tree-node> 
</template> 

樹node.html

<template> 
    <div>${name}</div> 

    <div class='childNodes'> 
     <!-- Something like this is the intend --> 
     <tree-node repeat.for="node of children"></tree-node> 
    </div> 
</template> 
+0

您可以將它添加到DOM並對其調用「增強」,但是一般情況下,如果您試圖動態添加東西到DOM中,您就知道它們將要去哪裏,所以我建議使用'compose'自定義元素 –

回答

2

我不能做到這一點使用自定義元素聲明。我不知道是否有辦法設置自定義元素的視圖模型。您可以使用compose作爲解決方法。

樹view.html

<template> 
    <require from="./tree-node"></require> 

    <!-- Something like this is the intend --> 
    <compose repeat.for="node of rootNodes" view="./tree-node.html" view-model.bind="node"></compose> 
</template> 

樹node.html

<template> 
    <div>${name}</div> 

    <div class='childNodes' style="margin-left: 20px;"> 
     <!-- Something like this is the intend --> 
     <compose repeat.for="node of children" view="./tree-node.html" view-model.bind="node"></compose> 
    </div> 
</template> 

運行例如https://gist.run/?id=95b8892918d7e5a7aadf0ac7eb28124d

另一種解決方案(在我看來更好)被曝光namechild可綁定屬性:

export class TreeNode { 
    @bindable value; 
    @bindable name; 
    @bindable children = []; 
} 

這樣,你就可以做這樣的事情:

<tree-node repeat.for="node of rootNodes" name.bind="node.name" value.bind="node.value" children.bind="node.children"></tree-node> 

這是多一點冗長,但速度更快。同時,我會看看是否有辦法設置自定義元素的視圖模型。

+0

我不知道可粘結解決方案如何應對深層嵌套對象,因爲孩子可能包含孩子等等。如果我將它用作可綁定屬性並不意味着整個對象必須被序列化爲一個可用作html屬性的字符串? – Fionn

+0

不,它不是!當你使用'property.bind'時,框架將進行變量賦值。沒有字符串序列化。 –

+0

必須考慮這一點,但有沒有辦法將元素本身綁定到創建的實例?像: Fionn

1

你在說什麼是Aurelia的核心功能。 請參閱​​

通過創建一個組件,您現在可以使用該組件在任何HTML爲<mycomponent></mycomponent>

組件可以含有其他成分。

+1

我想你的意思是不同的。我正在尋找一種以編程方式實例化組件的方式(新的MyComponent()),並在視圖中將標籤鏈接到創建的實例。主要是因爲組件可能有複雜的數據模型。 – Fionn

相關問題