Let's say you have a list of elements, and you want to apply some javascript behaviors to each element.
One way of doing this is to use prototype's built-in DOM selector to retrieve the list of elements and apply the appropriate function to each element.
This is ok if you have one, two or maybe three elements in the list, but what if there are 20, or even 200 elements. And better yet, what if the list was dynamic. You would have to constantly add an observer for new elements, and cleanup observers for deleted elements.
A better approach is to add a single behavior to the parent. By observing the parent, you're able to capture events triggered by all of it's children as well. Then we can add conditional logic to apply a function to only the child elements we care about.
We can also call differentiate function calls based on the child.
<ul id="parent">
<li class="child-1">One</li>
<li class="child-2">Two</li>
<li class="child-3">Three</li>
</ul>
One way of doing this is to use prototype's built-in DOM selector to retrieve the list of elements and apply the appropriate function to each element.
var children = $('parent').getElementsBySelector('li');
children.invoke('observe', 'click', function(e){
e.observe('click', function(event) { alert(e.innerHTML); }
});
This is ok if you have one, two or maybe three elements in the list, but what if there are 20, or even 200 elements. And better yet, what if the list was dynamic. You would have to constantly add an observer for new elements, and cleanup observers for deleted elements.
A better approach is to add a single behavior to the parent. By observing the parent, you're able to capture events triggered by all of it's children as well. Then we can add conditional logic to apply a function to only the child elements we care about.
$('parent').observe('click', function(event) {
var e = Event.element(event);
if(e.tagName != 'LI') return;
alert(e.innerHTML);
});
We can also call differentiate function calls based on the child.
$('parent').observe('click', function(event) {
var e = Event.element(event);
if(e.tagName != 'LI') return;
switch(e.className) {
case 'child-1':
alert("it's a boy!");
break;
case 'child-2':
alert("it's a girl!");
break;
case 'child-3'
alert("this one's a mistake!");
break;
}
});
Sorry, comments are closed for this article.