Class.Binds for MooTools is Back

Friday, January 23rd, 2009 @ 11:26 am | filed under: Code Releases

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:

[js]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(){

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:

[js]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);
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.

4 Responses to “Class.Binds for MooTools is Back”

  1. Sean McArthur Says:

    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.

  2. Aaron N. Says:

    As a side note, I’ll point out that having Specs to test this stuff makes development WAAAYYY easier.

  3. Tim Lund Says:

    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.

  4. Aaron N. Says:

    You can use .pass as you like still, of course. The only thing done for you is the binding.