Hello
I am trying to see if a fragment of an JavaScript code can be changed within a function using "onClick". Is there a method of changing the "filterCarsByColour" to "filterCarsByMake" using an onClick function?
const filterMe = filterCarsByColour(cars)
const filterMe = filterCarsByMake(cars)
I was not able to find an ideal example of this within the web or within Stackoverflow as most of the example only include changing the innerHTML object. So any help, recommendations or directions to other posts would be truly appreciated.
2 Answers
Instead of trying to change the function, it would be best to seperate those options and give the user the ability to select what type of filter they are after:
const filterBtn = document.querySelector('#filterBtn');
filterBtn.onclick = () => {
const type = document.querySelector('#type').value;
if (type === 'colour') {
// TODO: execute filterCarsByColour function
console.log('running filter by colour...');
} else if (type === 'make') {
// TODO: execute filterCarsByMake function
console.log('running filter by make...');
} else {
// ERROR: Type not defined
}
};
<select id="type">
<option value="colour">By Colour</option>
<option value="make">By Make</option>
</select>
<button id="filterBtn">
Filter
</button>
Comments
You need to parameterize the filtering function you want yo use :
const makeFilter = (filterFunction) => { ... };
const FilterMe = makeFilter(byCar)(cars, "Red");
The makeFilter function should return a two arguments function which takes data as first arg, filtering argument as second (to follow your example).
Not sure about the "onClick" reference, but if you need dynamicity you could look and choose using the event:
const filteringFunctions = {
byCar() {},
byColour() {}
};
domNode.addEventListener("click", e => {
const fn = filteringFunctions[e.target.getAttribute("data-filter")];
if (typeof fn === "function") {
// apply the filter if a function was found
const filterMe = makeFilter(fn)(cars, "red");
}
});
filterCarsByColour(cars, 'Red')andfilterCarsByColour(cars, 'Blue')should produce two different results; there should be no need to change the function itself.