public
Last active

private pattern mutator for Mootools 1.3.x

  • Download Gist
kenta.Private.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
/*
---
 
name: kenta.Private
 
description: Private mootator for MooTools 1.3.x
 
license: MIT-style license.
 
copyright: Carlesso Cristian http://mykenta.blogspot.com
 
requires: Class.PatternMutators
 
provides: private pattern mutator, '~' cleanup method.
 
...
*/
 
(function(){
var Private={};
Class.defineMutator(/^private\s(.*)/,function(fn, name){
var getPrivate = function(bind){
var uid= $uid(bind);
return Private[uid] || (Private[uid] = {});
};
this.define('~', function() {
var uid = $uid(this);
delete Private[uid];
});
this.define(name, function(){
var priv = getPrivate(this);
var args = Array.from(arguments);
args.push(priv);
var res = fn.apply(this, args);
return res;
});
});
})();

This is the Private pattern mutator for mootools 1.3.x
it requires the Class.PatternMutators from Mark Obcena

This mutator gives to your objects access to a special object that can't be accessed from other classes,
in order to use this object you only need 4 things:

* use a string to define your method name
* add 'private ' string in front of your method name
* add a parameter to your method, the mutator will automagically pass the private object as last parameter.
* when you've done call the '~' method

Example:

var Test = new Class({
    Implements:[Options],
    'private initialize':function(options, _private){
        this.setOptions(options);
        _private.test = 'Hello, '+ (options.name || 'world!');
    },
    'private say':function(i_can_call_this_as_i_want){
        alert(i_can_call_this_as_i_want.test);
    },
    a_normal_method:function(){
        alert("I don't use privates");
    }
});

    var kenta = new Test({name:'kenta'});
    kenta.say();
    kenta.a_normal_method();

    var test2 = new Test({});
    test2.say();

    //when done
    test2['~']();
    kenta['~']();

run this snippet

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.