Manual persistent component properties

[Warning]Warning

There is very little reason to implement persistent component properties manually. Using the <property-specification> element is much easier.

Tapestry uses the same mechanism for persistent component properties as it does for persisting page properties (remember that pages are, in fact, specialized components). Implementing transient and persistent properties inside components involves more work than with pages as 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 other page event interfaces, such as PageRenderListener 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 4.7. Manual Persistent Component Properties

package mypackage;

import org.apache.tapestry.Tapestry;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.event.PageDetachListener;
import org.apache.tapestry.event.PageEvent;
	
public class MyComponent extends BaseComponent implements PageDetachListener
{
    private String _myProperty;
    
    public void setMyProperty(String myProperty)
    {
        _myProperty = myProperty;
        
        Tapestry.fireObservedChange(this, "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.