Nesting Components

Components can be nested inside each other simpley by creating a new instance of a Component in its parent.

class Example extends Component {
    this.subComponent = new RodentOfUnusualSize();
}

The child Component can then simply be referenced by its parent.

draw(args:any): Promise<JQuery> {
    return new Promise((resolve) => {
        let $page = this.getTemplate("content");
        this.subComponent.draw().then(($content) => {
            this.$view.find("#rodent-holder").append($content);
        });
        return $page;
    });
}

Communicating from the child to the parent is as simple. When creating the child Component - simply pass in the parent, and code up the recieve() method.

class Example extends Component {
    subComponent = new RodentOfUnusualSize(this);

    //call a method on the sub-component
    subComponent.getData();

    // the method name "recieve" is hard coded
    recieve(data: any): void {
        console.log("Recieved data:", data);
    }
}

Then in the child Component call the emit() method to return data to the parent. When a parent is passed in its existance is identified by a UUID on Component.parent so you can check its there.

class RodentOfUnusualSize extends Component {
    getData(): void {
        config.api.getDataFromRemoteResource().then((response) => {
            if(this.parent)
                this.emit(data);
        });
    }
}

Recieving data

The data recieved by the recieve method is enhanced with details of its origin. The Component.emit() method will wrap the supplied data thus:

// source Component
let sampleData = [1,2,3,4,5,6];
this.emit(data);

// emit method
protected emit(data: any): void {
    let reply = {
        src: this.constructor.name,
        data: data
    };
    // reply passed to the parent Component
}

// recieve method
recieve(data: any): void{
    console.log("recieved: ", data);
}

// actual data
{
    src: "SourceComponent",
    data: [1,2,3,4,5,6]
}

results matching ""

    No results matching ""