How to Get data-mage-init Config in Custom Magento jQuery Widget

frontendmagento2requirejs

I am currently creating custom jquery widget for owl-carousel just to learn how to do it properly in magento-2.

I have configured my own module in requirejs-config.js at theme level.

var config = {
    map: {
        '*': {
            'carousel': 'js/carousel',
            'owlcarousel': 'js/owlcarousel/owl.carousel',
        }
    },    
    shim: {
        'owlcarousel': {
            deps: ['jquery']
        },
        'carousel': {
            deps: ['jquery','owlcarousel']
        }
    }
};

and then inside carousel.js I am setting like below

define([
    'jquery',
    'owlcarousel'
], function($) {
    'use strict';
    $.widget('custom.slider',{

        _create: function(config,element) {
            $(this.element).owlCarousel(config);
        }
    });

    return $.custom.slider;
});

and finally call inside .phtml template with below code.

<div class="custom-element" data-mage-init='{"carousel":{"items": 11}}'>
</div>

Still I am not seeing owl-carousel being loaded with my config that I am passing into data-mage-init.

Please tell what I am doing wrong?

EDIT-

If I write like this, it doesn't work.

_create: function(config,element) {
  this.element.owlCarousel(config);
}

But with this it does.

_create: function(config,element) {
    this.element.owlCarousel(this.options);
}

Best Answer

  1. Copy owl.carousel.js to app/design/frontend/<pakage_name>/<theme_name>/web/js/owl-carousel/.
  2. Add your requirejs module app/design/frontend/<pakage_name>/<theme_name>/web/js/carousel.js.

    define([
        'jquery',
        'owlCarousel'
    ], function($) {
        return function(config, element) {
            $(element).owlCarousel(config);
        };
    });
    
  3. Add requirejs config to app/design/frontend/<pakage_name>/<theme_name>/requirejs-config.js.

    var config = {
        map: {
            '*': {
                'carousel': 'js/carousel',
                'owlCarousel': 'js/owl-carousel/owl.carousel'
            }
        }
    };
    

How to use:

  • use the data-mage-init attribute to insert Owl Carousel in a certain element:

    <div class="owl-carousel" data-mage-init='{"carousel":{"option": value}}'>
        <div class="item">Item 1</div>
        ...
        <div class="item">Item n</div>
    </div>
    
  • use with <script type="text/x-magento-init" />:

    <div id="owl-carousel" class="owl-carousel">
        <div class="item">Item 1</div>
        ...
        <div class="item">Item n</div>
    </div>
    
    <script type="text/x-magento-init">
    {
        "#owl-carousel": {
            "carousel": {"option": value}
        }
    }
    </script>
    

You can modify the code according to your need.

I have used above code in one of my project to add carousel.

Original answer is at https://magento.stackexchange.com/a/227649/1968

Related Topic