javatapestry

Communicating with parent component


I have the MyPage.tml page and MyComponent.tml component.

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
    <body>
        <t:mycomponent />
    </body>
</html>

I need to display some data on MyPage based on what has happened in MyComponent. How can I make some data from MyComponent available to MyPage? Is there something like "reverse" parameters (child passing parameter to parent)?


Solution

  • Your component is available to you within your page as a variable where you can access the variables required from within your page like so:

    @Component(id = "myComponent")
    private MyComponent myComponent;
    
    @SetupRender //or any other render event method
    private void setup() {
        Object compVariable = myComponent.getYourVariable();
    }
    

    More elegant if you ask me is to use event bubbling as it makes it easer to refactor some logic out to a deeper component if needed.

    Component:

    @Inject
    private ComponentResources resources;
    
    @SetupRender //or any other lifecycle event method
    private void triggerEvent() {
        Object yourVariable = new Object();
        resources.triggerEvent("YOUR_EVENT_NAME", new Object[]{yourVariable}, null);
        //add an event callback if needed where I use null here
    }
    

    Page:

    @OnEvent(value = "YOUR_EVENT_NAME")
    private void handleComponentEvent(Object yourVariable) {
        //do something with yourVariable
        //even return something which would then can be handled by your component callback handler
    }