0

I try to call the same method from an object instance itself as well as from a EventListener. In this method I need to access some object attributes/methods via this. This does not work with the EventListener since in case the this var does not refer to the object instance but to the element that triggered the EventListener. Minimal example here:

function App() {
  this.selectBox = document.querySelector("#foo");
}

App.prototype.run = function() {
  this.selectBox.addEventListener('change', this.selected, false);
  this.selected();
}

App.prototype.selected = function() {
  // In this method 'this' referes to the App instance in case of the
  // call on line 7.
  // if the method in called via EventListener (line 6), this referes 
  // to the element that triggered the EventListener. In this case I am
  // not able to access any properties or methods of the object instance.

  var t = document.querySelector("#this");
  t.innerHTML = JSON.stringify(this);

  var o = document.querySelector("#out");
  o.innerHTML = this.selectBox.value;
}

a = new App();
a.run();
<select id="foo">
  <option>1</option>
  <option>2</option>
  <option>3</option>
</select>

<div>SELECTED: <span id="out"></span></div>
<div>'this' in method/callback is: <span id="this"></span></div>

https://jsfiddle.net/7eayc9ks/5/

Is there any (idiomatic) way to pass the required instance information (eg. a reference to the object instance) into the EventListener callback?

t.niese
  • 39,256
  • 9
  • 74
  • 101
sontags
  • 3,001
  • 3
  • 19
  • 25

0 Answers0