Skip to main content

Drupal 8 Js, how to create a global Drupal Js function

Recently i had to apply a "filter" JS function in various custom javascript libraries. One custom module was using a filter for a custom search page and another was using the same filter to another page and then i had to apply the same filter in my custom js theme.  This is how i used Drupal (in core JS functionality to add a custom filter function to the Drupal JS Object).

/**
 * Attaches the single_datetime behavior.
 *
 * @type {Drupal~behavior}
 */
(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.leafletCurrentLocation = {
    attach: function (context,drupalSettings) {

      Drupal.applyPoiFilters = function(activeFilters, poiFilters) {

          //Do stuff here
      }


    }
  }
})(jQuery, Drupal, drupalSettings);

Now i can call Drupal.applyPoiFilters wherever i want in any js file. The only "catch" here is to declare properly (with the right dependencies) your custom js library in your custom.libraries.yml file.

Your custom.libraries.yml file should look like this:

search_results:
  version: VERSION
  css:
    theme:
      css/search_results.css: {}
  js:
    js/search_results.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

Jquery and Jquery.once are used in my custom module js file although are not shown in the above example.

javascript custom module