Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden Features of MooTools

What are the hidden or obscure features of MooTools that every MooTools developer should be aware of?

One feature per answer, please.

like image 1000
artlung Avatar asked Nov 03 '11 17:11

artlung


2 Answers

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.

like image 149
Dimitar Christoff Avatar answered Oct 30 '22 22:10

Dimitar Christoff


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.

like image 43
arian Avatar answered Oct 30 '22 22:10

arian