MooTools: Track Class Instances With the TrackInstances Mutator

It’s great to track all of your classes’ instances for debugging purposes or mass altering.

Huh? Mass Altering?

For instances of some Audio/Video player classes: stop/pause all players

For instances of positioned elements: recalculate position of all elements upon window resize

Call hide method of all instances of a class upon an event

I needed it more than once and I used to track instances from within any class I needed it:

123456789101112131415

varMyClass=newClass({initialize:function(){MyClass.instances.push(this);},recalcPosition:function(){// something that recalculates position or any other task that should happen on all instances}});MyClass.instances=[];// from another code:MyClass.instances.each(function(instance){instance.recalcPosition();});

However, I got too many classes with this behavior. I ended up writing a MooTools Class Mutator to automate the process:

varMyClass=newClass({initialize:function(){},TrackInstances:true,recalcPosition:function(){// something that recalculates position or any other task that should happen on all instances}});varx=newMyClass();vary=newMyClass();MyClass.instances;// [x, y]MyClass.instances.length;// 2// from another code:window.addEvent("resize",function(){MyClass.instances.each(function(instance){instance.recalcPosition();});});

The only constraint is that the “initialize” declaration in an object should be prior to the TrackInstances:true. That’s because mutators are called in the same loop as all other methods, and if the loop didn’t get to a certain method, then the mutator won’t know it. According to thesetickets, the MooTools team won’t fix it anytime soon.