element onclick in class never called

Viewed 42

I have a simple class.

The problem im having is that my onClick function is never called when clicking on the div element.

class card {
  constructor(parent, element) {
    this.parent = parent;
    this.element = element;

    this.element.on({
      'click': $.proxy(this.onClick, this)
    });
  }

  onClick() {
    console.log("onclick");
  }

}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];

    this.element.children(".card").each((obj) => {
      this.cards.push(new card(this, $(obj)));
    });

  }
}

var my_a = new cards();
1 Answers

each(index, element) passes two parameters to the callback. The first is the index, the second is the element. You are wrapping the index, not the dom element.

Each docs

class card {
  constructor(parent, element) {
   
    this.parent = parent;
    this.element = element;
    
    this.element.on({
      'click': $.proxy(this.onClick, this)
    });
  }

  onClick() {
    console.log("onclick");
  }

}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];
    

    this.element.children(".card").each((obj, el) => {    
      console.log(el);      
      this.cards.push(new card(this, $(el)));
    });

  }
}

var my_a = new cards();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="cards">
one
asdf

  <div class="card">
  card 1
  asdf
  </div>
  
  <div class="card">
  card 2
  asdf
  </div>


</div>

Related