Rupert Madden-Abbott
Rupert Madden-Abbott

Reputation: 13278

Problems with 'this': How do I access both an element and a class inside an addEvent function?

This is probably best explained through some code. I know that in the following example, the this inside the addEvent method is the current element contained in the array elements.

var testClass = new Class({
    testMethod: function() {
        var elements = $$('.elements');
        elements.addEvent('click', function() {
            console.log(this) //This will log the current element from elements
            });
        }
    });

I also know that in the following example, this instead refers to the class testClass because I have utilised the bind method.

var testClass = new Class({
    testMethod: function() {
        var elements = $$('.elements');
        elements.addEvent('click', function() {
            console.log(this); //This will log the class testClass
            }.bind(this));
        }
    });

My question, then, is how do I access both the class and the current element at the same time in addEvent?

Please note that if elements were not an array, this would not be problematic as I could pass elements as a parameter in the bind method. However, as it is an array, I cannot do this as it would simple give me an array of all the elements instead of the current element. Thanks!

Upvotes: 1

Views: 80

Answers (1)

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827496

You can provide an argument event argument to your event handler function, for example:

var TestClass = new Class({
  testMethod: function() {
    var elements = $$('.elements');
    elements.addEvent('click', function(e) {
      console.log(this);     // the object instance
      console.log(e.target); // <--- the HTML element
    }.bind(this));
  }
});

MooTools will pass a normalized event object as the e argument of your event handler function, there you can access the e.target property which will refer to the DOM element that triggered the event.

Upvotes: 3

Related Questions