When you are debugging a huge web app, comprised of many classes and many methods, it can be really tedious and difficult. Having to go and edit code and add console.log
calls all over the place is hardly productive and can involve a lot of typing. Fortunately, you can use a lesser known feature of MooTools called ‘Class Mutators’ to change the prototype of your class and automatically log calls to your methods of interest.
// define the mutator as 'Monitor', use as Mointor: ['methodname', 'method2'...] Class.Mutators.Monitor = function(methods){ if (!this.prototype.initialize) this.implement('initialize', function(){}); return Array.from(methods).concat(this.prototype.Monitor || []); }; Class.Mutators.initialize = function(initialize){ return function(){ Array.from(this.Monitor).each(function(name){ var original = this[name]; if (original) this[name] = function() { console.log("[LOG] " + name, "[SCOPE]:", this, "[ARGS]", arguments); original.apply(this, arguments); } }, this); return initialize.apply(this, arguments); }; };
What this does is defines a class mutator called ‘Monitor’, which can be added to any class declaration. It accepts either a single method name (as string) or an array of method names that you would like to log.
In your class, this will look like this:
var foo = new Class({ Monitor: 'bar', initialize: function() { this.bar("mootools"); }, bar: function(what) { alert(what); } }); var f = new foo(); f.bar.call({hi:"there from a custom scope"}, "scope 2");
When the code runs, you will see in your console the 2 calls to the monitored method, indented by method name, the scope and the arguments it has received.
This can save your life. Play on jsfiddle: http://jsfiddle.net/BMsZ7/2/ 🙂
Very usefull! I will use this.
It’s just like Class.Mutators.Binds. I only wonder if that will still work since Class.Mutators.initialize in Class.Binds.js is overridden.
David walsh was the reason I started MooTools, you are the reason I continue with it. Thanks pal.
lol, best. comment. ever 🙂 thanks