Aaron Newton has made a new version of the Binds mutator that's used just like the one I've shown here, but works with MooTools 1.2.
When writing a Class you often want to bind a class method to an event and access this as the instance of the class. You could say this isn't a big deal using .bind(). That's right until it comes to removing the event again, since Function::bind works in that way that it returns a new function wrapping the old one. Hence you need to store that very function when you want to remove it again (without removing all events from that element, which isn't good inside a portable class).
What I've seen a couple of times is an object holding all bound functions and created in the constructor, example:
I wasn't quite happy with this solution, because it's too verbose: why always use this.bound.myFn when I always want the bound one? Secondly, I don't want to do the binding of all these functions by hand. After some discussions on different solutions this is what I come up with as the optimum between speed (don't worry its faster than the solution above) and usability.
var MyClass = new Class({ initialize: function(){ this.bound = { sayHello: this.sayHello.bind(this), sayGoodbye: this.sayGoodbye.bind(this) } // now only using this.bound.sayHello and // this.bound.sayGoodbye inside the class }, sayHello: function() { /* ... */ }, sayGoodbye: function() { /* ... */ } });
A new so called "class mutator" named Binds. Most of you probably didn't hear of class mutators before, but you sure have used a class mutator before when you've written one or another class. Built in mutators are
Implements and Extends and here is the code of the Binds mutator:What it does is overriding all methods passed to it as a string with a version bound to the instance.
Class.Mutators.Binds = function(self, methods) { $splat(methods).each(function(method){ var fn = self[method]; self[method] = function(){ return fn.apply(self, arguments); }; }); };
Binds: 'foo' would just bind foo to the class, Binds: ['foo', 'bar'] binds foo and bar. Pretty simple, huh?Now let's see how the class can be simplified using the Binds mutator:
var MyClass = new Class({ Binds: ['sayHello', 'sayGoodbye'], initialize: function(){ // now only using this.sayHello and // this.sayGoodbye inside the class }, sayHello: function() { /* ... */ }, sayGoodbye: function() { /* ... */ } });
I hope you learned a bit again or can find use of it.
If you have any wishes or ideas for further articles let me know.