将其他信息传递到EventListener回调中

时间:2019-01-01 14:41:45

标签: javascript

我尝试从对象实例本身以及从EventListener调用相同的方法。在这种方法中,我需要通过this访问一些对象属性/方法。这不适用于EventListener,因为万一this var不是引用对象实例,而是引用触发EventListener的元素。这里的最小示例:

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/

是否有(惯用的)方法将所需的实例信息(例如,对对象实例的引用)传递到EventListener回调中?

0 个答案:

没有答案