I'm setting up multiple Algolia/autocomplete fields in a ES6 class, I would like to extract the onSelect handler, so I could use some data_attributes in the HTML node, But I can't figure out how to do it.
Here is my JS class:
import { autocomplete } from '@algolia/autocomplete-js';
export default class AutocompleteSetUp {
init() {
document.querySelectorAll('.entity-autocomplete').forEach(elem => {
this.autocomplete_elem_setup(elem);
});
}
autocompleteSelectionHandler(some params) {
console.log('I NEED TO PERFORM SOME ACTIONS HERE');
}
autocomplete_elem_setup(htmlNode) {
autocomplete({
container: htmlNode,
// DYNAMIC SEARCH
getSources({ query }) {
return fetch(
`/artists.json?query=${query}`
)
.then((response) => response.json())
.then((data) => {
return [
{
sourceId: `artists`,
getItems() {
return data;
},
getItemInputValue({ item }) {
return item.name;
},
// ...
templates: {
header() {
return 'Suggestions';
},
item({ item }) {
return `Artist: ${item.name}`;
},
footer() {
return 'Powered by Algolia Autocomplete';
},
},
onSelect({ item }) {
console.log(item);
console.log('container:', htmlNode );
console.log('source:', source );
// Here I'm able to perform some actions
// But I need to extract this code in another function in the class:
// How can I call autocompleteSelectionHandler ?
// This doesn't work:
this.autocompleteSelectionHandler(some_params);
},
},
];
});
},
});
}
}
To be honest, I would love to also exact other handlers for "clean_codeness" (like item in templates), but I need to call several methods in onSelect so I really have no choice.