Programming

Javascript Events

My goal or focus with events are as follows:

  • Object decoupling through Event programming
  • Event Cross Browser Standardization
  • Simplicity ( Minimize on bloat, complexity and use precedent standards. )

Custom Events

After reading this article on Creating Custom Events with JavaScript: Decoupling I was inspired and wrote an implementation not dependent on Prototype.js.

Here is a simple custom event example:

//function to be executed when event is dispatched
function dumpTime( e )
{
	var time = e.data.time;
	var hours = time.getHours()
	var minutes = time.getMinutes()
	var seconds = time.getSeconds()
 
	e.data.target.innerHTML = hours + ":" + minutes + "." + seconds;
}
 
//Here the event is added to the element in question
document.getElementById( "time" ).addCustomEventListener( "time-update", dumpTime, false );
 
//Here is a simple function set to execute once a second. 
//When this function executes it dispatches the "time-update" event.
window.setInterval(function(){dispatchEvent( "time-update", {time: new Date() } )}, 1000);