Integrations / Platforms / Magento 2 / Front-end Custom Events
May. 10, 2019

Front-end Custom Events

Autocomplete menu events

You can adjust all the logic of the autocomplete.js integration by registering a custom method in your JS file. Registering of a hook can be done by using algolia JS object.

You can learn how to add a custom JS file in a Create a custom extension tutorial.

Possible hooks:

  • beforeAutocompleteSources(sources, algoliaClient)
    • can be used to modify default datasources
    • the hook must return sources variable
  • beforeAutocompleteOptions(options)
    • can be used to modify default options of autocomplete menu
    • the hook must return options variable

Those hooks will be triggered right before it initializes the autocomplete feature.

Example of the hooks:

1
2
3
4
5
// modify default sources
algolia.registerHook('beforeAutocompleteSources', (sources, algoliaClient) => sources);

// modify default options
algolia.registerHook('beforeAutocompleteOptions', options => options);
  • afterAutocompleteStart(algoliaAutocompleteInstance)
    • can be used to observe events on the autocomplete element
    • the hook must return algoliaAutocompleteInstance variable

Example of the hook:

1
2
// bind new event on the autocomplete element
algolia.registerHook('afterAutocompleteStart', algoliaAutocompleteInstance => algoliaAutocompleteInstance);

Instant search page events

You can adjust all the logic of the InstantSearch.js integration by registering a couple of custom hooks:

By registering a hook in your JS file, you can directly modify it’s parameter which must be returned back from the method.

Example of the beforeInstantsearchInit(instantsearchOptions) hook:

1
2
// modify default instantsearchOptions
algolia.registerHook('beforeInstantsearchInit', instantsearchOptions => instantsearchOptions);

Example on how to add a new toggle widget to instant search page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
algolia.registerHook('beforeWidgetInitialization', allWidgetConfiguration => {
  const wrapper = document.getElementById('instant-search-facets-container');

  const widgetConfig = {
    container: wrapper.appendChild(createISWidgetContainer('in_stock')),
    attributeName: 'in_stock',
    label: 'In Stock',
    values: {
      on: 1
    },
    templates: {
      header: '<div class="name">Is on stock</div>'
    }
  };

  if (typeof allWidgetConfiguration['toggle'] === 'undefined') {
    allWidgetConfiguration['toggle'] = [widgetConfig];
  } else {
    allWidgetConfiguration['toggle'].push(widgetConfig);
  }

  return allWidgetConfiguration;
});

All default widgets can be found in allWidgetConfiguration object and can be removed or modified in this method.

Did you find this page helpful?