T5这么多的Page Lifecycle method, 应该怎样使用?

Tapestry5种大概有以下Page Lifecycle methods.

void pageLoaded();
void pageAttached();
void pageDetached();

void/Object onActivate();
void/Object onActivate(params);

pageLoaded事件会在一个page class在被创建时创建调用。
pageAttached会在page class被创建时和每次tapestry request一个页面时调用。
pageDetached会在每次page class放回页面池时调用。 注意:最好不要有这个方法在页面,如果存在的话tapestry不会自动reset page class中的instance变量。

onActivate 会在页面render前的时候调用。
onActivate(params);这个也是会在页面render前的时候调用。只是这个接受page context变量(参数)。

促发的顺序是。

pageLoaded
pageAttached
onActivate
onActivate(params)
pageDetached

不过pageLoaded不一定在每次render page时都会触发。 因为它只在被创建时调用。

这里的话估计很多人都会问 pageAttached  onActivate 有什么区别。 我这里说说在开发时遇到的奇怪问题。

比如我们有两个页面 Index, Second. 如果在Index页面中有个PageLink组件page是Second。 这样当我打开Index页面时, Second的pageAttached方法也被调用了。 本来我的判断用户是否登入是在BasePage的pageAttached方法里面的,Index不需要登入, Second需要登入。 这样的话会调用Second的pageAttached这样就使页面转到Login page了。

我们应该把判断用户是否登入逻辑放到onActivate方法中, 这样当打开Index页面时,不会调用到Second的onActivate方法。

知道上面的情况,我们就应该把page class 变量初始化代码放在onActivate中而不是放到pageAttached方法里。

 

 

在项目中使用onActivate做权限控制,到后来发现很多问题。 有时候页面需要有参数的onActivate方面, 会搞得非常麻烦。 在看过http://www.nabble.com/T5-onActivate-td17673637.html#a17673637 和tapestry5 jumpstart http://202.177.217.122:8080/jumpstart/examples/lang/methods 发现。

onActivate不适合用来做权限控制和页面开始render的初始化值。 页面初始化值应该在setupRender里。

引用tapestry maillist中的别人说的一句话

 

写道
I just read the tail end of the conversation, but I wanted to add something.

I try to use onActivate to capture parameters from the url, and maybe do minimal translation/validation of those inputs. But I do the actual work within the setupRender. That way it doesn't matter how many onActivates get called and what order, they are only there to translate url parmaters into page variables which then drive setupRender ( with proper if not nulls, etc ).

This might simplify your mental model of how the code is split up and is supposed to work.


You would have to put some thought though if you use a form on a page, since the setupRender is not called on form submit.. If you look at the different events that the form lifecycle provides, you'll see that you just have to refactor your setupRender logic into a third method that is called from setupRender and an approriate onEvent from the form ( onPrepareForForm, or onPrepareSubmitForForm, something like that ).

 这里有片文章提供简便的方法实现权限控制: http://wiki.apache.org/tapestry/Tapestry5HowToControlAccess

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值