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 ><span ></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);
});
CodePudding user response:
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 ><span ></span>${value}</div>`;
if ($(".checked-filter").find(`.${value}`).length === 0) {
$(".checked-filter").prepend(filter);
}
$(document).on("click", ".selectedFilter", e => {
this.resetThisFilter($(e.target));
});
}