Using .bind(this)

0 views
Skip to first unread message

VirtuosiMedia

unread,
Aug 26, 2008, 4:51:31 PM8/26/08
to MooTools Users
Could anyone explain to me in what situations 'this' should be bound
and perhaps provide a few examples? I keep running into problems in
writing classes and I think that my lack of understanding of when and
how to use it is one of the major difficulties. I've looked at the
documentation in the mootorial and in the docs section, but the
explanations on binding are cursory at best. Any help would really be
appreciated. Thanks.

tr0y

unread,
Aug 26, 2008, 5:27:02 PM8/26/08
to MooTools Users
As I understand it, .bind lets you pass a variable to the bound
function, making the "this" within the function refer to the bound
variable...

$('netTween_set').addEvent('click', newTweenSet.bind(newTween));

In this case, newTween is the tween object and newTweenSet is the
function.

Now, inside the function newTweenSet, using "this" will refer to
newTween, letting you write something like this:

var newTweenSet = function() {
this.start('width', '300px');
}

Hope this answers your question.

VirtuosiMedia

unread,
Aug 26, 2008, 5:47:02 PM8/26/08
to MooTools Users
So just to clarify, binding will cause the scope for this to refer to
the current function rather than the global space?

virtualgadjo

unread,
Aug 27, 2008, 11:38:38 AM8/27/08
to MooTools Users
hi,

just a word because i think the question could concern the bind usage
inside a class
a little example, a very, very useful class :)))
#############"
var toto = new Class ({

Implements: Options,

options: {
message: "toto"
},

initialize: function(elem, options){
this.setOptions(options);
this.alternateMessage = "a message";
this.elem = elem;
this.elem.addEvent('click', function(){
this.alternateMessage = "other message";
this.aMethod();
}.bind(this));
},

aMethod: function(){
alert(this.options.message);
}

});
##################
in this class, you can see two effects of this binding in this
function

this.elem.addEvent('click', function(){
this.alternateMessage = "other message";
this.aMethod();
}.bind(this));

- this.alternateMessage is now changed for the whole class, not only
inside the fucntion as this refers to the class
- without binding the click function with .bind(this) the result would
be "this.alternateMessage has no properties", "this.aMethod() is not a
function"
binding the function to the class (this) allows it to use any method
or this.var set inside it

hope it'll help

have swing

VirtuosiMedia

unread,
Aug 27, 2008, 2:58:25 PM8/27/08
to MooTools Users
That example helped a lot. Thank you very much.
Reply all
Reply to author
Forward
0 new messages