Every node has a .children
property. It is an Array
containing all the child nodes. You can also set the children array directly with an array of elements, or even patch objects.
this.tag('List').children = items.map((item, index) => {
return {
type: ExampleListItem,
item: item,
x: index * 70,
}
})
Child list
Also, there is the childList
property which has several methods to change the current children configuration.
Name | Description |
---|---|
add(item : Element) | Append child |
addAt(item : Element, index : number) | Add child at the specified index |
setAt(item : Element, index : number) | Replaces the child at the specified index by the specified child |
replace(item : Element, prevItem : Element) | Replaces the previous item with the new item |
getAt(index : number) : Element | Returns the view at the specified index |
getIndex(item : Element) : number | Returns the indexOf the view |
remove(item : Element) | Returns the specified view |
removeAt(index : number) | Returns the element at the specified index |
clear() | Removes all children |
a(o) | Appends a child or literal patch object |
getByRef(ref : String) : Element | Returns the child element with the specified ref |
get length() : number | The number of children |
get first() : Element | The first view |
get last() : Element | The last view |
sort(f : Function) | Sort the children using the sort function |
Live demo
class TemplateDemo extends lng.Application {
static _template() {
return {
x: 20, y: 20,
List: { type: ExampleList }
}
}
_init() {
// let's generate dinamically some list items
// and give it to our list
this.tag('List').items = [1,2,3,4].map((i) => ({label: i }))
}
}
class ExampleList extends lng.Component {
set items(items) {
this.children = items.map((item, index) => {
return {
type: ExampleListItem,
x: index * 70, //item width + 20px margin
item //passing the item as an attribute
}
})
}
}
class ExampleListItem extends lng.Component {
static _template() {
return {
rect: true, w: 50, h: 50, color: 0xffff00ff, alpha: 0.8,
Label: {
x: 25, y: 30, mount: .5
}
}
}
_init() {
this.patch({ Label: { text: { text: this.item.label }}})
}
}
const options = {stage: {w: window.innerWidth, h: window.innerHeight, useImageWorker: false}};
const app = new TemplateDemo(options);
document.body.appendChild(app.stage.getCanvas());