Home > Software engineering >  element onclick in class never called
element onclick in class never called

Time:12-09

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();

CodePudding user response:

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 >
one
asdf

  <div >
  card 1
  asdf
  </div>
  
  <div >
  card 2
  asdf
  </div>


</div>

  • Related