When Tapestry creates a page property automatically, it creates basic getter and setter methods that do nothing but retrieve or set the value of the property. But sometimes we might want to put some functionality into the getter and/or setter methods. In the GuessTheWord application, for example, we might want to do something depending on the length of the word submitted by the user and write a setter like this: public void setTheWord(String theWord) {
if (theWord != null) { int length = theWord.length();
// Do something… }
this.theWord = theWord; } This might be not be a very convincing example, but believe me, sometimes you just cannot avoid writing some code in a getter or a setter. And as soon as you have provided a getter or a setter of your own, you have to write all the remaining code yourself. So Tapestry will not take care of setting theWord to null; you’ll need to do that yourself too. In Tapestry 3, page classes have a very convenient method for this purpose, initialize(). In Tapestry 4, this method still exists but it is deprecated. So it is not recommended that we use it, and I should not be mentioning it here. But still, this method is more convenient than the alternative solution and I have to admit that I use the deprecated initialize() method in my work. It looks like this: protected void initialize() { theWord = null; } As soon as we have provided this method in our page class, it will be called every time the page instance is sent to the pool, so we have achieved what we wanted. The alternative approach, recommended for use in Tapestry 4, is to implement the PageDetachListener interface and its only method pageDetached(PageEvent event). So if you do everything properly, your Home class will look like this: public abstract class Home extends BasePage implements PageDetachListener {
private String theWord;
private void setTheWord(String theWord) { this.theWord = theWord; }
public String getTheWord() { return theWord; }
public void pageDetached(PageEvent event) { theWord = null; }
public String onWordSubmit() { return "Secret"; } } For me, it’s just the same result with more coding, but of course the creators of Tapestry know better.
blog comments powered by Disqus |
|
|
|
|
|
|
|