1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Pat Tate
  • 23
  • 1
  • 3
  • 1
    you seem to use an odd mix of mootools + jquery. your class is mootools but dom events are jquery. seems unclean - you should stick to mootools code in the class throughout if possible. if classes is all you use mootools for, then just grab http://www.moo4q.com/ - mootools classes for jquery. pointy's answer for keeping a reference will work fine. if you want to point the click event to a class method (cleaner), then you can `this.newdiv.addEvent("click", this.handleClick.bind(this))` in native mootools. – Dimitar Christoff Apr 25 '11 at 13:11

1 Answers1

2

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.)

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    that's correct, scope will be the `event.target` element, unless you use `function.bind()` - careful with `$()` returning jquery tho. `$(this.newDiv).click(function() { ... }.bind(this));` will also work fine. – Dimitar Christoff Apr 25 '11 at 13:14
  • @Dimitar - The object referenced by the `this` keyword is not scope, they are entirely different things. – RobG Apr 25 '11 at 14:09
  • yes, agreed, this is just a context object pointer that will likely be either the global object (window), the class instance or an element pointer here. since it's a function, it gets a scope chain dependent on context and `this` is not directly related as vars canbe in the scope chain that have nothing to do with it. cheers – Dimitar Christoff Apr 25 '11 at 16:06