3

I can't get the mageInit binding to work on a custom jQuery widget which I have created.

I have used it in my KO template like:

<div data-bind="mageInit: {'mywidget':{'configuration-value':true}">

But in the chrome inspector I can see that it does not load the JS file for my widget.

However, when I try adding a one of Magento's own jQuery widgets it works.

<div data-bind="mageInit: {'accordion':{'collapsible': true}}"></div>

Also, I can get my own custom widget to work in a phtml template with...

<div data-mage-init='{ "mywidget": {"configuration-value":true} }'>

I created my jQuery widget by adding the following code.

Namespace/Module/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            mywidget: 'Namespace_Module/js/my-widget'
        }
    }
}

Namespace/Module/view/frontend/web/js/my-widget.js

define([
    'jquery',
    'jquery/ui'
], function($) {
    "use strict";

    $.widget('mage.mywidget', {
        _create: function() {
            // Init code
            console.log('test1');
        }
    });

    return $.mage.mywidget;
});

In the above piece of code I've used the mage namespace, but I've also tried using holy. It doesn't make a difference either way and Im unsure which is correct.


I have also tried using the full path to my widget in the mageInit binding...

<div data-bind="mageInit: {'Namespace_Module/js/my-widget':{'configuration-value':true}">

Also I looked at where magento declares the mageInit binding, vendor/magento/module-ui/view/base/web/js/lib/knockout/bindings/mage-init.js, but I can't see why it won't work when I use it for my custom jQuery widget.


UPDATE

Following the call stack it seems these files are all responsible for initialising components which use the mageInit binding.

  • lib/web/mage/bootstrap.js ln 20
  • lib/web/mage/apply/main.js ln 24 (Initializes components assigned to a specified element via data-* attribute.)
  • vendor/magento/module-ui/view/base/web/js/lib/knockout/bindings/mage-init.js ln 20
  • 2
    In your code of KO bindings, you are missing a }. "mageInit: {'mywidget':{'configuration-value':true}" should be "mageInit: {'mywidget':{'configuration-value':true}}" – Jaimin Sutariya Aug 7 '18 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.