samedi 25 juin 2016

Attaching an object method to an event while retaining the element reference

function MyObject() {
  this.name = "";
  this.elements = document.getElementsByClassName('myClass');
}

MyObject.prototype.attachEventHandlers = function() {
  for (var i = 0; i < this.elements.length; i++) {
    this.elements[i].addEventListener('click', this.myEventHandler);
  }
};

MyObject.prototype.myEventHandler = function() {
  // Here "this" referst to the element that the event invoked on:
  console.log(this.innerHTML);

  // Is there a way to get the name property like:
  // console.log(this.name);
  // without passing the instance as an argument?
};

var myObject = new MyObject();
myObject.name = "Foo";
myObject.attachEventHandlers();

I would like to use the myEventHandler method as an even handler, but as you know in event handlers this refers to the element that that the event was invoked on.

I would like to both keep a reference to the element that the event was invoked on, and also keep a reference to the object instance.

There are two ways I can think of:

  1. Passing the object instance as an argument to the event handler, like:

    // ...
        var that = this;
        this.elements[i].addEventListener('click', function() {
          that.myEventHandler(that);
        }
    // ...
    
    MyObject.prototype.myEventHandler = function(that) { // ...
    
    
  2. The same as above, but instead of using the prototype method, using an inline function.

I'd rather not use an inline function, as it clutters the code. And I'd rather not pass the object instance as an argument, if I don't have to.

Is there a more idiomatic and simpler way to achieve this?

Aucun commentaire:

Enregistrer un commentaire