Manual Persistent Component Properties

Implementing transient and persistent properties inside components involves more work. The fireObservedChange() method is available to components as well as pages, but the initialization of the component is more complicated.

Components do not have the equivalent of the initialize() method. Instead, they must register for an event notification to tell them when the page is being detached from the engine (prior to be stored back into the page pool). This event is generated by the page itself.

The Java interface PageDetachListener is the event listener interface for this purpose. By simply implementing this interface, Tapestry will register the component as a listener and ensure that it receives event notifications at the right time (this works for the two other page event interfaces, PageRenderListener and PageCleanupListener as well; simply implement the interface and leave the rest to the framework).

Tapestry provides a method, finishLoad(), for just this purpose: late initialization.

Example 2.7. Manual Persistent Component Properties

public class MyComponent extends BaseComponent implements PageDetachListener
{
    private String _myProperty;
    
    public void setMyProperty(String myProperty)
    {
        _myProperty = myProperty;
        
        fireObservedChange("myProperty", myProperty);
    }
    
    public String getMyProperty()
    {
        return _myProperty;
    }
    
    protected void initialize()
    {
        _myProperty = "a default value";
    }
    
    protected void finishLoad()
    {
        initialize();
    }
    
    /**
     *  The method specified by PageDetachListener.
     *
     **/
    
    public void pageDetached(PageEvent event)
    {
        initialize();
    }
}

Again, there is no particular need to do all this; using the <property-specification> element is far, far simpler.