views:

39

answers:

1

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!

+3  A: 

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.

CMS
Ah yes that does it! You legend! Thanks :).
Rupert
Note that `e.target` is not guaranteed to be an element in `$$('.elements')`. It may be a descendant child instead, since `click` bubbles.
Crescent Fresh
@Crescent, yeah, I should be more explicit in my last line. Glad to see you back around :)
CMS
to avoid the bubbling issue, your only guarantee is to fix it upriver - do the .each loop on the elements manually which will give you an element token you can refer to: `elements.each(function(el) { el.addEvent('click', function(e) { console.log(el); }.bind(this); }, this);`
Dimitar Christoff