Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper technique to add listeners to DOM created via an XTemplate?

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?

like image 982
Upperstage Avatar asked Nov 10 '11 13:11

Upperstage


People also ask

What method do we use to create an event listener?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

How do you find event listeners in a DOM node?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

What is an event listener?

An event listener is a procedure or function in a computer program that waits for an event to occur. Examples of an event are the user clicking or moving the mouse, pressing a key on the keyboard, disk I/O, network activity, or an internal timer or interrupt.


1 Answers

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>

To assign handler to the anchors you would do in jquery something like:

$('.nav a').live('click', function(){
    // do something on anchor click
});

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.

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'
    });

For more info take a look at docs for the Ext.Element.addListener method.

like image 154
Molecular Man Avatar answered Oct 11 '22 11:10

Molecular Man