Confusion On Using Mootools And The 'This' Keyword
I开发者_如何学运维 am trying to assign an event handler to a class I have created in Mootools but I cannot seem to access any of the variables that I created for the class. Like so:
var newPerson = new Class({
initialize: function(name)
{
this.firstName = name;
//-------Creating Div----------//
...........
//--------Created Div----------//
$(this.newDiv.id).click(function()
{
alert("clicked");
};
};
Now when I change the function to alert the objects assigned name alert(this.firstName);
it doesn't access them and I can't figure out why.
Could anyone point my in the right direction?
At the top of the "initialize" function, add a variable declaration:
var thisObj = this;
Now, in your handler, you should be able to do:
alert(thisObj.firstName);
By stashing this
as it stood when the "initialize" function began, you provide a way for the "click" handler to get at the original object. In the handler, this
will refer to the DOM element involved with the event. (I'm actually guessing about that, because I'm not really familiar with MooTools.)
精彩评论