PART 1.2.5 – jQuery widgets and require.js

Useful resources:

http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/javascript/js_init.html

http://requirejs.org/

http://inchoo.net/magento-2/custom-javascript-in-magento-2-with-requirejs/

Initializing js

data-mage-init

Example from layered navigation in Luma (theme-frontend-luma/Magento_LayeredNavigation/templates/layer/state.phtml)

When inserted in a certain element, the script is called only for this particular element. It is not automatically called for other elements of this type on the page.

<script type=”text/x-magento-init”>

Example from add to cart module-catalog/view/frontend/templates/product/view/addtocart.phtml  

To call a JS component on a HTML element without direct access to the element or with no relation to a certain element, use the <script type=”text/x-magento-init”> tag and attribute.

Components

http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/widgets/jquery-widgets-about.html 

Some of the common ones include:

  • Accordion
  • Collapsible
  • Dropdown
  • Modal

Gallery widget

http://devdocs.magento.com/guides/v2.1/javascript-dev-guide/widgets/widget_gallery.html

 

Example of how to add a new javascript

In the root of your theme add: a file named requirejs-config.js 

requirejs-config.js 

 

requirejs-config.js

/**

 * Copyright © 2009-2017 Vaimo Group. All rights reserved.

 * See LICENSE.txt for license details.

 **/

 

var config = {

    “map”: {

        “*”: {

            example: “js/example”

        }

    }

};

Create the js file

 

js/example.js

/**

 * Copyright © 2009-2017 Vaimo Group. All rights reserved.

 * See LICENSE.txt for license details.

 **/

define([

    ‘jquery’

], function($) {

    $.widget(“vaimo.example”, {

        options: {

            color: ‘#fafafa’

        },

 

        _create: function () {

            console.log(‘This is the background color: ‘ + this.options.color);

        }

    });

});

Initialization using data-mage-init

 

<footer data-mage-init=‘{“example”:{“color”: “#fab”}}’ class=“footer content”>

    

class=“footer__cms accordion accordion-container”>

        

class=“accordion-title footer__title”>

            

class=“footer__title-header”>

                echo __(‘Customer service’) ?>

            

        

        

class=“accordion-content footer__cms-links”>

            echo $block->getChildHtml(‘footer.links’) ?>

        

    </div>

</footer>

 

 

Exercise 8.0

  1. Create a js file in your theme.
  2. Include the js file using require-js.
  3. Intiate the js using data-mage-init on the div with the class products inside list.phtml (the template used in exercise 6)
  4. The script should add a class, color or console log a string when the product list is rendered.