Aarto Aarto - 1 month ago 14
HTML Question

javascript bind object in event creation

I'm actually getting stuck on a simple (pretty sure it is) example.

<div id="first">first</div>
<div id="second">second</div>
<script>
var JSClass = {
element : null,
click : function() {
console.log(this.element.id);
},
created : function(element) {
this.element = element;
this.element.addEventListener('click', this.click.bind(this));
}
};
JSClass.created(document.querySelector('#first'));
JSClass.created(document.querySelector('#second'));
</script>


By binding the entire object when I create the event I should obtain "first" when I click on the first element and "second" when I click on the second element but it's not the case.
It's fully functional for other objects I use but this simple case doesn't work...

Answer

You can use class, set this.element to element passed to constructor

<div id="first">first</div>
<div id="second">second</div>
<script>
  class JSClass {
    constructor(element) {
      this.element = element;
    }
    created() {
      this.element
        .addEventListener('click', this.click.bind(this));
    }
    click() {
      console.log(this.element.id);
    }
  };
  let first = new JSClass(document.querySelector('#first'));
  let second = new JSClass(document.querySelector('#second'));
  first.created();
  second.created();
</script>