event-node.mustache revision fb1ecdf65fd4106deb62da339763f2e7670ca0f6
2N/A<link href="{{componentAssets}}/node.css" rel="stylesheet" type="text/css">
2N/A<div class="intro">
2N/A <p>This example demonstrates how to use events with <code>NodeList</code> instances.</p>
2N/A <p>Clicking a box will update its content.</p>
2N/A</div>
2N/A
2N/A<div class="example">
2N/A{{>event-node-source}}
2N/A</div>
2N/A
2N/A<h2>Setting up the NodeList</h2>
2N/A<p>First we need some HTML to work with.</p>
2N/A```
2N/A<ul id="demo">
2N/A <li><p>i am <em>lorem</em></p></li>
2N/A <li><p>i am <strong>ispum</strong></p></li>
2N/A</ul>
2N/A```
2N/A<h2>Handling Events</h2>
2N/A<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>
2N/A<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>
2N/A```
2N/A var onClick = function(e) {
2N/A e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
2N/A this.addClass('yui-pass');
2N/A };
2N/A```
2N/A
2N/A<h2>Attaching Events</h2>
2N/A<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>
2N/A```
Y.all('#demo li').on('click', onClick);
```
<h2>Complete Example Source</h2>
```
{{>event-node-source}}
```