Class.Binds for MooTools is Back
A while ago Jan Kassens authored a mutator for MooTools classes that allowed you to auto-bind methods to the instance of the class. This let you do the following:
var MyClass = new Class({
Binds: ['say'],
initialize: function(element, message) {
this.el = $(element);
this.message = message;
},
monitor: function(){
this.el.addEvent('click', this.say); //say is already bound to 'this'
},
stopMonitoring: function(){
this.el.removeEvent('click', this.say); //again, say is already bound to 'this'
},
say: function(){
alert(this.message);
}
});
The benefit here is that the methods you enumerated in the Binds were automagically bound to the instance of the class. (Read a little more on Jan’s post as to the various reason’s you want to do this).
When MooTools 1.2 came out the inner-workings of Class prevented Jan’s work from working. I released a mix-in class because I was under the impression that you couldn’t get this type of mutator (which modifies the instance that a class creates rather than the class constructor itself) to work in 1.2. Well, I figured out how to do it (mostly after looking over the work that’s been done for a private member mutator) and now it’s back. Here’s the entire code:
Class.Mutators.Binds = function(self, binds) {
if (!self.Binds) return self;
delete self.Binds;
var oldInit = self.initialize;
self.initialize = function() {
Array.flatten(binds).each(function(binder) {
var original = this[binder];
this[binder] = function(){
return original.apply(this, arguments);
}.bind(this);
this[binder].parent = original.parent;
}, this);
return oldInit.apply(this,arguments);
};
return self;
};
And it works just as the first example above. This is available in my plugins library, of course.
Follow @clientcide on twitter to get notified of new posts.
To follow me personally on twitter, follow @anutron.

January 23rd, 2009 at 12:01 pm
Awesome. That problem you mention is exactly what I had to work around at first. When I wrote the Privates mutator, and got it all working, I instantiated a couple objects, and realized they were sharing the same privates object.
Then realized I had to do all the magic for each instance. Cool to see it helped here.
January 23rd, 2009 at 12:25 pm
As a side note, I’ll point out that having Specs to test this stuff makes development WAAAYYY easier.
January 28th, 2009 at 2:22 pm
This is pretty sweet, and will certainly make alot of my code more pretty. I still do have alot of calls which require one time arguments, which I don’t like saving to the instanced class..
Please correct me if I missed something here, and you indeed can pass arguments with the calls.
January 28th, 2009 at 4:08 pm
You can use .pass as you like still, of course. The only thing done for you is the binding.