4

I need to overwrite/extend the component JavaScript (e.g.: script for the Carousel which is located here /sitecore/media library/Base Themes/Components Theme/Scripts/component-carousel) files to add additional requirements or improve accessibility.

What is the best practice to do that in SXA?

1 Answer 1

2

Starting form SXA 1.7 we've added an option to extend the component's script and we are using it also in the SXA to change the behaviour of few components in the Edit mode. You can create new Theme which will be extending our scripts or include those scripts in your current theme.

Here is how this is done in SXA. Navigate to /sitecore/media library/Base Themes and you should see similar structure:

enter image description here

Basically, we use JavaScript decoration to extend component's scripts. Here is a content (trimmed a little bit) of /sitecore/media library/Base Themes/Editing Components/Scripts/component-carousel-edit:

XA.component.carousels && XA.component.carousels.initInstance && (XA.component.carousels.initInstance = (function (func, $) {

    var disableEmptySlides = function(component) {
        // custom logic which is disabling empty slides in the Edit mode for the Carousel
    }

    var beforeInitScript = function (component, prop) {
        // code which will be run before initialization of the rendering
    }

    var afterInitScript = function (component) {
        // script which will be used after the component has been initialized in the original script
        $(document).ready(function() {
            disableEmptySlides(component);
       });      
    }

    return function (component, prop) {
        try {
            var _prop = beforeInitScript(component, prop);
        } catch (e) {
            console.log(e)
        }

        var answer = func.apply(this, [component,_prop]);

        try {
            afterInitScript(component);
        } catch (e) {
            console.log(e)
        }

        return answer;
    }

})(XA.component.carousels.initInstance, jQuery))

So, in general, we have a pattern to use beforeInitScript() and afterInitScript() and in that way, we are extending original script.

Editing Components theme is added as one of base themes of /sitecore/media library/Themes/YOUR_TENANT/YOUR_SITE/Editing Theme base theme.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.