Skip to main content

Shopware6 - Storefront - custom JS-extension containing event listeners

Category: Shopware
shopware-logo

This is just a short example how to register javascript event listeners to storefront components in Shopware6. 

src/Resources/storefront/main.js

import ContribNamePluginNameEventHandler from './contrib-name-plugin-name/contrib-name-plugin-name-event-handler.plugin';

// Register them via the existing PluginManager
const PluginManager = window.PluginManager;
PluginManager.register('ContribNamePluginNameEventHandler ', ContribNamePluginNameEventHandler , '.product-image');

// add an additional plugin if you like
//PluginManager.register('ContribNamePluginNameFacyStuff', ContribNamePluginNameFamcyStuff, 'document');

src/Resources/storefront/contrib-name-plugin-name/contrib-name-plugin-name-event-handler.js

import Plugin from 'src/script/plugin-system/plugin.class';

export default class ContribNamePluginNameEventHandler extends Plugin {
    init() {
        this._registerEvents();
    }

    _registerEvents() {
        this.el.addEventListener('mouseover', this._updatePreview.bind(this));
    }

    _updatePreview() {
        console.log('mouseover');
    }
}

For enabling your JS-extension, the storefront components need to get rebuild.

./psh.phar storefront:build