Event Factoring / Normalization
Please note this is a DRAFT!
When creating a rich and interactive web applications it can be very easy to have a large number of event handlers attached to many elements. On top of the chance of making you code cumbersome difficult to maintain it also bloats your HTML not to mention have an effect on resources.
A prime example is a list. Concider the following HTML.
- Test 1
- Test 2
- Test 3
var eRA;
window.onload=function()
{
eRA = document.getElementById("ResultArea");
}
function liHovered(el)
{
eRA.innerHMTL = "Hovering : " + el.innerHTML;
}
funciton liOut()
{
eRA.innerHMTL = "Hovering : Nothing";
}
As with all most all languages DOM events bubble. This bubbling of events allows you to place handlers higher up in the hierarchy and then using some simple logic to calculate the elements that fired the event.
Below is a simple example of factoring normalization these event handlers. You need to pas the event and for that you are able to determine what eleemnts rasized the event, thus what to do.
- Test 1
- Test 2
- Test 3
var eRA;
window.onload=function()
{
eRA = document.getElementById("ResultArea")
};
function liHovered(e, bOver)
{
// This line is actually not needed for this example.
e = e || event;
// Browsers have slightly different event objects.
// Either eventObj.srcElement or eventObj.target
// will contain the element that fired the event
var el = e.srcElement || e.target;
if( el.nodeType == 3 && el.tagName == "LI" )
{
// At this point you can be sure the the li
// is hovering so you can manipulate like before
if( bOver ) eRA.innerHMTL = "Hovering : " + el.innerHTML;
else eRA.innerHMTL = "Hovering : Nothing";
}
}
Once you have understood this, concider using attaching to the document and use a collection of classes and element types to determine what happens.