Binding a function to any class method in MooTools

Published July 8th, 2008

Some time back, while experimenting with MooTools, I found myself with the requirement to be able to call a function whenever a particular method on a given class was called. In effect, I needed to treat the class’s method as an event and fire a particular function when the method was called.

So I wrote a very small addition to the Mootools’ own Class code, which allowed this. The new method, Class.bindFunctionToMethod(), allows you either to intercept the method call before or after it’s fired. If fired before you can change the arguments being passed in, while if fired after then you can alter the return value.

Of course you need to be careful how you use it: by ‘piggy-backing’ on method calls like this (especially if you alter the arguments or return value) you’re potentially altering the script’s behaviour in a way that’s not necessarily evident by looking at the classes themselves.

You can download the code here: it’s heavily commented, so it should be fairly obvious how to use it. It works just fine with MooTools version 1.1+ and 1.2.

Get a Trackback link

No Comments Yet

Be the first to comment!

Leave a comment

Comment Policy: First time comments are moderated. Please be patient.

OpenID

Anonymous