event-node.mustache revision 07dcb72a9c4129c6ab13ec15033906e55e4c0d47
<link href="{{componentAssets}}/node.css" rel="stylesheet" type="text/css">
<div class="intro">
<p>This example demonstrates how to use events with <code>NodeList</code> instances.</p>
<p>Clicking a box will update its content.</p>
</div>
<div class="example">
{{>event-node-source}}
</div>
<h2>Setting up the NodeList</h2>
<p>First we need some HTML to work with.</p>
```
<ul id="demo">
<li><p>i am <em>lorem</em></p></li>
<li><p>i am <strong>ispum</strong></p></li>
</ul>
```
<h2>Handling Events</h2>
<p>Next we will add a handler to run when the event is fired. In our handler we will update the node with the <code>type</code> of the event.</p>
<p>Note that the event handler receives an event object with its <code>currentTarget</code> set to the current Node instance, and the actual node clicked as the <code>target</code>. The context of the handler is the NodeList instance, so <code>this</code> refers to our NodeList instance.</p>
```
var onClick = function(e) {
e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
this.addClass('yui-pass');
};
```
<h2>Attaching Events</h2>
<p>We can assign our handler to all of the items by using the <code>all</code> method to get a <code>NodeList</code> instance and using the <code>on</code> method to subscribe to the event.</p>
```
Y.all('#demo li').on('click', onClick);
```
<h2>Prefer `node.delegate()` over `nodelist.on()`</h2>
<p>Sometimes you need to create individual subscriptions for each Node in a NodeList (as is done in this example), but usually it's preferable to <a href="../event/index.html#event-delegation">use event delegation</a>.</p>
<h2>Complete Example Source</h2>
```
{{>event-node-source}}
```