Event handlers are a common cause of memory leaks and can cause performance degradation when not managed carefully. The more event handlers we create the more likely we are to introduce such problems, so we should try to avoid creating huge numbers of handlers when we don't have to.
Event delegation is a technique where a single event handler is created on a parent element, which leverages the fact that the browser will bubble any events raised on one of its children to this parent element. If the target of the original event matches the delegate's selector then it will execute the event handler, otherwise nothing will happen.
This means that instead of attaching an event handler to each individual child element, we only have to create a single handler on the parent element and then, within the handler, query which child element was actually clicked, and react appropriately.
Example:
Attach an event handler to the list's click event and specify we want to delegate
this event to the list items (that is LI tags), by passing a configuration object to
the on method's fourth argument, containing the delegate property:
Event delegation is a technique where a single event handler is created on a parent element, which leverages the fact that the browser will bubble any events raised on one of its children to this parent element. If the target of the original event matches the delegate's selector then it will execute the event handler, otherwise nothing will happen.
This means that instead of attaching an event handler to each individual child element, we only have to create a single handler on the parent element and then, within the handler, query which child element was actually clicked, and react appropriately.
Example:
<div id='mydiv'>
<li>1</li>
<li>2</li>
<li>3</li>
</div>
Attach an event handler to the list's click event and specify we want to delegate
this event to the list items (that is LI tags), by passing a configuration object to
the on method's fourth argument, containing the delegate property:
Ext.get('mydiv').on('click', function(e, target, options){
alert(target.innerHtml);
}, this, {
delegate: 'li'
}
}
本文探讨了事件处理器可能导致内存泄漏的问题,并介绍了一种通过事件委托来优化性能的方法。该方法仅需在一个父元素上设置事件监听器,利用事件冒泡机制处理子元素的事件,从而减少事件处理器的数量。
1486

被折叠的 条评论
为什么被折叠?



