domenica, ottobre 09, 2011

MooTools private pattern mutator

UPDATE: I created a MooTools forge repository for Private. There you will find any kind of improvement ;) /UPDATE Not too long ago I wrote this gist to add a sort of private properties / private methods to MooTools 1.2.x:

As of MooTools 1.3 this gist won't work anymore, but I've wrote another one as alternative, it requires Mark Obcena's PatternMutators.js that you can find here: keeto.PatternMutators.js:
How it works?

In the first version, the one for the 1.2.x branch of MooTools, if you Implements Private, what happens under the hood is that it create a property using MooTools $uid to get a unique-id per istance on a not-accessible outside of Class.Mutators.Private function, then it rewrote all the method of your instance passing the associated property as the last parameter of your function so that you can use it to store/retrieve private properties or even methods.

Since there's no way to automate the cleaning of all the objects/methods you can add, it need also to add a '~' method that you need to call on your destructor so it will not leak memory. I decided to use this ugly syntax: ['~']() because it need to stand out of your code, in a way to remember you that you are using an ugly hack to create privates and because is easier to remember something so strange ;)

For the 1.3 and upper branches of MooTools(yep, still work on 1.4.x) I decided to use a different, not compatible, way to achieve the same objective, so I based my mutators on keeto's patternMutator, for a number of reasons, basically cleaner syntax, re-using of existing code (keeto's one), and only methods marked with 'private' are now overwritten. You can see an example right here:

The code is slighly different, instead of Implements:[Private], you have to explicity mark the method you would like to use private properties or methods by adding 'private ' ahead of your method name, but other things remains unchanged.

2 commenti:

Unknown ha detto...

This is now a part of mootools milk (2.0) - the mutator definition akin to keeto's way.

Unknown ha detto...

https://github.com/mootools/Base/blob/master/Source/Core/Class.js