Analytics & Reports
Analytics

Mixins

Mixins are a set of reusable functions and properties that can be shared across tags. If you apply a mixin to a tag, the functions and properties on that mixin are available as properties on that tag.

Example

Here is an example of how to define mixins:

javascript
new storefront({
  ...
  mixins: {
    global: {
      shouldUpdate: (stateChange, nextOpts) => true,
    },
    custom: {
      tracking: {
        trackClick: (e) => trackerService.click(e);
      },
    },
  }
});

There are 2 kinds of mixins.

  • global gets applied to all tags
  • custom are defined within the tag itself and only apply to that tag
Property Type Default
global GlobalMixin {}
custom CustomMixins {}

global

The mixin to automatically apply to all tags. This mixin is applied after all the standard StoreFront mixins are applied, so it can be used to override StoreFront functionality.

Important

The lifecycle function init() cannot be overridden by the global mixin.

Property Type Default Required
shouldUpdate boolean | ({ state: object }, object) => boolean false

shouldUpdate

A function to determine if a component should update. StoreFront provides its own shouldUpdate function that makes a component update only if it has changed, but it is not enabled by default.

  • true: Use the StoreFront-provided function.
  • false: Disable shouldUpdate and always allow components to update.
  • function: Use the given function instead. The function should return true if the component should update and false otherwise. The first argument to the function is an object with the property state that contains the new state of the component, and the second argument contains the new props of the component.

custom

Named mixins that are available on-demand to tags.

To apply one of these mixins, add this to your tag’s constructor:

this.mixin(<name_of_mixin>);

To illustrate, with the mixins configured in the example at the top, you can apply the custom mixin tracking like so:

constructor() {
  this.mixin('tracking');
}

Then you can use the trackClick() function defined in the mixin in your JavaScript like this:

this.trackClick(e);

Or you can use it in your HTML like this:

<gb-button on-click="{ trackClick }">Click Me</gb-button>