Mootools Bind Function

Published on:

Well it’s my first blog entry for a little while (I have a few almost ready to publish) and its going to be a short one.

I have been doing a lot of client side scripting work recently, mostly with the Mootools framework, if you havn’t heard of it then it’s definitely worth a look, it is a really powerfull javascript framework made of modules that you can pick and mix in, meaning that it is increadably lightweight when compared to the likes of prototype etc.

One really cool little function is the bind function. The bind function is prototyped to the function element and so is called directly upon a function. When calling bind you pass it an element to which the ‘this’ of the function then corresponds to. A demonstration is probably in order!

element.addEvent('focus', function(e) {
    alert(this.id)
})

The above code would attach the focus event to ‘element’, on focus the browser would alert the id of that element.

element.addEvent('focus', function(e) {
    alert(this.id)
}.bind(element2))

This time the alert would output the id of element2. This practise is particularly handy within classes, meaning that the event listener can be bound to the instance of the class, and not the element that is firing the event.

Hope that helps someone!

Matt