What are the hidden or obscure features of MooTools that every MooTools developer should be aware of?
One feature per answer, please.
Class Mutators
MooTools has a wonderful feature that allows you to create your own Class mutators. Eg, to add a logger for particular class methods being referenced, you can do:
// 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);
};
};
and then in the Class:
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");
Try the jsfiddle: http://jsfiddle.net/BMsZ7/2/
This little gem has been instrumental to me catching nested bugfoot race condition issues inside a HUUUGE async webapp that would have been so difficult to trace otherwise.
Function.prototype.protect
is maybe a lesser known nice one.
Is used to have protected methods in classes:
var Foo = new Class({
fooify: function(){
console.log('can\'t touch me');
}.protect(),
barify: function(){
this.fooify();
}
});
var foo = new Foo();
foo.fooify(); // throws error
foo.barify(); // logs "can't touch me"
Personally I don't use it very often, but it might be useful in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With