For one, please use 'self' instead of 'that', it's more descriptive.

Secondly, there's a few base principles to understand. Let's first say
we define this in the global scope:
    var fn = function(one, two){
        console.log(this, one, two);
    }

Calling `fn('blaat', 'blurp')` will log: window, 'blaat', 'blurp'.

Every function has a `this` variable. It refers to the context the
function "belongs" to, which is normally the object it is used on:
    var myObject = {fn: fn};
    myObject.fn('blaat', 'blurp');
This will log: myObject, 'blaat', 'blurp'. Calling `fn('blaat',
'blurp')` will still log: window, 'blaat', 'blurp'.

You can also change the value of `this` in a function when you execute
it by using:
    fn.call(myObject, 'blaat', 'blurp');
or:
    fn.apply(myObject, ['blaat', 'blurp']);
In both cases, the function will log: myObject, 'blaat', 'blurp'.

Another thing you can do is `bind` a function to an object, telling it
to always have that object as `this`:
    var boundFn = fn.bind(myObject);
Calling `boundFn()` will log: myObject, 'blaat', 'blurp'.
If you would now do:
    var otherObject = {fn: boundFn};
    otherObject.fn('blaat', 'blurp');
It will log: myObject, 'blaat', 'blurp', since the boundFn was bound to
myObject.

Stripped down to the basics, fn.bind isn't much more than:
    function(thisArg){
        var self = this; // `this` refers to `fn` here.
        return function(){
            self.apply(thisArg, arguments);
        }
    }
So it returns a wrapped function which will always execute `self` (our
`fn`) with `thisArg` (our `myObject`) as `this`.


Now for the binding of your click-event-handler. The function you attach
would normally be executed with the element as `this`.
If you want to keep the reference of the element in your function like
that, you shouldn't bind it, and you can use `var self = this` to have a
reference to your Widget object as `self` in the function.
If you don't need to keep `this` as element (because you want to access
the element through `this.element` like in Ryan's example), you can bind
the function to your Widget object, and have your Widget object as
`this`.
Where you store the function (or if you want to at all) is up to you.
Ryan does it in a nice way by storing a bound version of the function in
a `this.bound` object. That way you can also easily remove the event
handler, by using `this.element.removeEvent('click',
this.bound.clickHandler)`.

I hope this clears up a few things.

Tim.


-- 
Tim Wienk, Software Developer, MooTools Developer
E. [email protected] | W. http://tim.wienk.name

Reply via email to