Count MooTools Events Per Element in MooTools 1.2

In: web resources

19 Jun 2009

Every once in a while I’ll need to check an element to see how many (usually 1 or 0) events of a specific type are tied to a specific element. Here’s how you can check how many events and of which type have been assigned to an element.

The MooTools Javascript

/* when the dom's ready */
window.addEvent('domready',function() {

	/* our element */
	var element = $('element-with-events');

	/* create custom event */
	Element.Events.customevent = {
		base: 'click',
		condition: function(event) {
			return 'garbage';
		}
	};

	/* add a bunch of different events */
	element.addEvent('click',function() { console.log('click event 1'); });
	element.addEvent('click',function() { console.log('click event 2'); });
	element.addEvent('resize',function() { console.log('resize event 1'); });
	element.addEvent('mouseenter',function() { console.log('mouseenter event 1'); });
	element.addEvent('mouseleave',function() { console.log('mouseleave event 2'); });
	element.addEvent('mouseleave',function() { console.log('mouseleave event 3'); });
	element.addEvent('mouseleave',function() { console.log('mouseleave event 4'); });
	element.addEvent('customevent',function() { console.log('customevent event 1'); });

	/* save a hash of the events */
	var events = new Hash(element.retrieve('events'));

	/* get the number of event types */
	console.log('# Of Different Events: ' + events.getLength()); // returns 5

	/* save the keys */
	var keys = events.getKeys();

	/* get the event types and how many per */
	console.log('Different Event Types: ' + keys.join(', ')); //returns 'click', 'resize', 'mouseenter', 'mouseleave', 'customevent'

	/* save the types, get the number of events per event type */
	keys.each(function(key) {
		console.log(new Hash(events[key]));
		console.log('# of ' + key + ' events: ' + new Hash(events[key]).keys.length);//returns 'click': 2, 'resize': 1, 'mouseenter': 1, 'mouseleave': 4, 'customevent': 1
	});

});

The source code above is pretty self explanatory (comments FTW!). Would you use this for anything?

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!

Comment Form

About this blog

This blog delivers stylish and dynamic news for designers and web-developers on all subjects of design, ranging from: CSS, Ajax, Javascript, web design, graphics, typography, advertising & much more. Our goal is to help you communicate effectively on the web with an engaging website or functional interface.