Event delegation will save the world.
If you ever wanted to know how many event handlers your Prototype.js-based application has, but were afraid to count, this tiny bookmarklet will gladly do that for you!
Accidentally, the snippet demonstrates an absolutely wicked use of Prototype’s sacred technique of inject over Hash.
$H(Event.cache).inject(0, function(m, p) {
m += $H(p.value).values().flatten().size();
return m;
});
Enjoy.
Radoslav Stankov said on Feb 19, 2009 @ 13:44
#1Nice one(bw you have one more ‘)’ in the end)
I generally use my CD3.Behaviors witch have very simple event-delegation build in, so I didn’t have more than 10 ~ 15 event handler, on one of my heavy js project. But on the other side those 10~15 could easy become 4~5/6 with some little effort :)
10x for sharing
kangax (article author) said on Feb 19, 2009 @ 19:38
#2Thanks, Radoslav.
I removed the extra parenthesis.
Zeno said on Feb 27, 2009 @ 16:26
#6Thanks for the nice snippet!
(It helped me debugging a situation in which I was accumulating too many events observers… caused by Low Pro’s reassignAfterAjax=true)
Phunky said on Mar 5, 2009 @ 7:06
#7This wouldn’t work for me :( does it require the latest version of PrototypeJS or would version > 1.6 be fine?
Sounds like a great little bookmarklet tho!
kangax (article author) said on Mar 5, 2009 @ 9:58
#8@Phunky
Should work with 1.6+. Which version are you having problem with?
Ana Wilson said on Mar 6, 2009 @ 13:51
#9Juriy:
I need a code ninja like you for a client of mine who is a MS MVP – he has a js project and only the best talent will do. Are you available for telecommuting consulting engagements? if you email me back I’ll send you my contact info.
Nrajlich said on Jun 9, 2009 @ 19:11
#11Just so you know, this breaks in Prototype 1.6.1 RC2, due to the new way of storing the Event cache. Here’s the fixed version:
Victor said on Dec 24, 2009 @ 1:40
#12the fixed version seems not work in 1.6.1
Burton Kent said on Feb 1, 2010 @ 16:58
#13If you check the <a href="http://www.prototypejs.org/2007/8/15/prototype-1-6-0-release-candidate"?release notes for 1.6.0 you’ll see that they note that “References to observed elements are no longer stored in an internal cache, to prevent leaks.” This may be part of the problem.