Simple MooTools Event / Class Binding

By  on  

One thing that can be difficult to wrap your head around is "binding." Binding allows you to use the this reference at times that you normally cannot. Let me show you how to use basic MooTools binding using an easy test case.

Lets pretend that we have a MooTools class created with a method called showMessage() which has the sole purpose of using JavaScript's alert() function to pop up a message. The message is an option, so its variable representation is this.options.message. This will work fine within any method, but the addEvent() throws things off.

The Problem MooTools Code

//more class code above....
	
	showMessage: function() {
		
		$('myelement').addEvent('click', function() {
			alert(this.options.message);
		});
		
	},
	

//more class code below

The addEvent() method of the Element causes the this.options.message reference to throw a JavaScript error. What we need to do here is bind the class to the event.

The MooTools Solution

//more class code above....
	
	showMessage: function() {
		
		$('myelement').addEvent('click', function() {
			alert(this.options.message);
		}.bind(this));
		
	},
	

//more class code below

We bind the class to the event's function and now can reference the class (and its options -- in this case its message option) by using this.

MooTools binding can be a difficult idea to understand. To learn more about binding, check out the MooTools documentation.

Recent Features

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Using MooTools to Instruct Google Analytics to Track Outbound Links

    Google Analytics provides a wealth of information about who's coming to your website. One of the most important statistics the service provides is the referrer statistic -- you've gotta know who's sending people to your website, right? What about where you send others though?

  • By
    Disable Autocomplete, Autocapitalize, and Autocorrect

    Mobile and desktop browser vendors do their best to help us not look like idiots by providing us autocomplete, autocorrect, and autocapitalize features.  Unfortunately these features can sometimes get in the way;  we don't always want or need the help they provide.  Luckily most browsers allow...

Discussion

  1. Do you want to learn more about binding?

    Let’s read this fantastic article by Cristophe Porteneuve:
    Getting Out of Binding Situations in JavaScript at A List Apart.

    Great Post!!

  2. A simple way of not even bothering with binding is to assign this to a different variable. I don’t use this myself, but it sounds good in theory:

     showMessage: function() {
        var me = this;
    
        $('myelement').addEvent('click', function() {
            alert(me.options.message);
        });
    
    }
    
  3. @Sean McArthur: That’s exactly what I ended up doing to get around this problem. Now that I’ve seen this post though, I’ll be converting my scripts to use bind instead :)

  4. what ‘s wrong in sean syntax… sometimes I use it too… It’s heavy in RAM usage or something like that?

  5. i just rewrite a commment, cause this thread interest me a lot.

  6. Great, your blog is a goldmine for web developers. I was looking for a solution for this problem.
    Can I reuse your post to do the same in French on my blog?
    Thanks.

  7. Mauro

    David.. you are simply a genius!!! every time I have a problem I find the solution on your website…. Binding is actually a hard thing to learn for my small brain.. but with your examples I always find my way!!

    THANK YOU!!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!