将侦听器添加到通过 XTemplate 创建的 DOM 的正确技术? [英] Proper technique to add listeners to DOM created via an XTemplate?
问题描述
我们使用 XTemplates - 很多 XTemplates.它们非常适合显示只读内容.但是您是否曾经向通过模板创建的 DOM 添加(Ext JS)侦听器?您愿意分享创建这些侦听器的首选技术吗?
We use XTemplates - lots of XTemplates. They are great for displaying read-only content. But have you ever added (Ext JS) listeners to DOM created via a template? Would you care to share your preferred technique for creating these listeners?
推荐答案
我的首选技术是使用 jquery 中 $.live
函数的模拟.F.i.假设您将使用 xtemplate 创建如下所示的简单列表:
My preferred technique is using the analog of $.live
function from jquery. F.i. let's assume you are going to use xtemplate for creating simple list like the following:
<ul class="nav">
<li><a href="example.com">item1</a></li>
<!-- ... -->
</ul>
要将处理程序分配给锚点,您将在 jquery 中执行以下操作:
To assign handler to the anchors you would do in jquery something like:
$('.nav a').live('click', function(){
// do something on anchor click
});
$.live
函数很棒,因为即使处理程序分配发生在列表呈现之前,它也能工作.当您使用 xtemplate 时,这一事实非常重要.
The $.live
function is great because it would work even if handler assignation would happen before list rendering. This fact is extremely important when you use xtemplate.
幸运的是,ExtJs 中有类似的东西——委托事件.直接看代码:
Fortunately there is analog in ExtJs - delegating events. Just look at the code:
Ext.getBody().on('click', function(event, target){
// do something on anchor click
}, null, {
delegate: '.nav a'
});
有关更多信息,请查看 docs.
For more info take a look at docs for the Ext.Element.addListener
method.
这篇关于将侦听器添加到通过 XTemplate 创建的 DOM 的正确技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!