1

I want to add an event listener inside a class after creating the corresponding element.

In my event listener inside the appendSelectedFilter function I want to refer to the clicked element. Since I can't use this in this context I tried to create a jQuery object and parse it to the resetThisFilter function, but the object has a length of 0.

What am I missing here? How can I parse the clicked object to another function?

class RecipeFilter {
  constructor(filterkategories, response) {
    this.filterkategories = filterkategories;
    this.response = response;
  }

  appendSelectedFilter(filterItem) {
    let value = filterItem.children[0].children[0].value;
    let filter = `<div class="selectedFilter ${value}" ><span class="icon-pk-close"></span>${value}</div>`;
    if ($(".checked-filter").find(`.${value}`).length === 0) {
      $(".checked-filter").prepend(filter);
    }
    $(document).on("click", ".selectedFilter", () => {
      this.resetThisFilter($(`.selectedFilter .${value}`));
    });
  }

  var recipeFilter = new RecipeFilter(filterkategories, response);
  recipeFilter.renderFilters(filterkategories);

  $(document).on("click", ".filter-list-item", function() {
    recipeFilter.appendSelectedFilter(this);
  });

1 Answer 1

1

Accept the Event object as an argument to your arrow function, then you can use the target property of the event to retrieve the element which the user clicked on:

appendSelectedFilter(filterItem) {
  let value = filterItem.children[0].children[0].value;
  let filter = `<div class="selectedFilter ${value}" ><span class="icon-pk-close"></span>${value}</div>`;
    
  if ($(".checked-filter").find(`.${value}`).length === 0) {
    $(".checked-filter").prepend(filter);
  }
    
  $(document).on("click", ".selectedFilter", e => {
    this.resetThisFilter($(e.target));
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Thats exactly what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.