将侦听器添加到通过XTemplate创建的DOM的正确技术? [英] Proper technique to add listeners to DOM created via an XTemplate?
问题描述
我们使用XTemplates-很多XTemplates。它们非常适合显示只读内容。但是,您是否曾经将(Ext JS)侦听器添加到通过模板创建的DOM中?您是否愿意分享创建这些侦听器的首选技术?
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?
推荐答案
我的首选技术是使用<$ c $类似物jquery中的c> $。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.
幸运的是,ExtJ中有类似的东西-委托事件。只需看一下代码即可:
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'
});
有关更多信息,请参见文档用于 Ext.Element.addListener
方法。
For more info take a look at docs for the Ext.Element.addListener
method.
这篇关于将侦听器添加到通过XTemplate创建的DOM的正确技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!