?> June 2018 - Addeos

Monthly Archive 27 June 2018

Magento 2 : How to add a jquery widget

When you need to add javascript in your magento 2, one solution is to implement a jQuery widget.
It's pretty simple and straight forward.
This is how to do it step by step.

1. In the phtml template, your need to specify the component that will be available for the dom element :

<script type="text/x-magento-init">
{
  “#dom-id": {
    “componentName": {}
  }
}
</script>

Here componentName will be available for #dom-id

2. Then add the require js config
In <namespace>/<module>/view/frontend/requirejs-config.js add :

var config = {
map: {
    '*': {
      componentName: 'Namespace_Module/js/component'
    }
  }
};

Here you specify that the component componentName will map <namespace>/<module>/js/component.
In other words it will map : /app/code/<namespace>/<module>/view/frontend/web/js/component.js

3. Then create the jQuery widget itself :

In /<namespace>/<module>/view/frontend/web/js/component.js
Add the following code :

define(['jquery','moment'], function ($, moment) {
      'use strict';

      $.widget('<namespace>.<module>', {
         _create: function () {
            Console.log(‘boo’);
          }
     });
     return $.<namespace>.<module>;
});

And that's it.