Home > OS >  es6 class find array object class from element
es6 class find array object class from element

Time:12-10

I have 2 classes parent/child. In the parent class I need a way to return/find the child class from the clicked on element.

I am getting: 'find(...).toggle is not a function'

Here in a minimal example:

class card {
  constructor(parent, element) {

    this.parent = parent;
    this.element = element;
  }

  toggle(expand) {
    //Do stuff
  }
}

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

    $(document).click((event) => {
      var clickedOn = $(event.target);
      var $thisClosest = clickedOn.closest(".card");

      find($thisClosest).toggle();
    });
  }

  find(element) {
    this.cards.forEach((obj, el) => {
      if ($(el) == element)
        return obj; // need to return the class card
    });
  };

}

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>

CodePudding user response:

You should use this.cards.find instead of this.cards.forEach as Array.forEach does not return any value.

Array.find will return first element from array that matches the condition.

find(element) {
  return this.cards.find((card) => card.element.is(element)));
};

I also used jQuery's .is() as a more robust way to compare elements.

  • Related