Magento 2 – Access Variables from Another Require JS Module

javascriptjquerymagento2requirejstemplate

Cannot understand how to organize JS/PHTML cross vars and functions calling for Magento 2 using Require.js.
The standard methods are not working. Made a lot of tries, but no success. Hope somebody help me.

Task: get the var value and call function in JS file from the script located in PHTML template

We have: requirejs-config.js, modu.js, ask.phtml

Code:

requirejs-config.js

var config = {
    map: {
        "*": {
            modu: "js/modu",
        }
    },
    deps: [
        "js/modu",
    ],
    paths: {
        modu: "js/modu",
    },
};

modu.js

define([
    "jquery",
    "domReady!"
], function($) {
    "use strict";

    var moduVar = 'ModuVar test var';

    function fromPhtml(x) {
        console.log(x);
    }

});

ask.phtml

<script>

require([
        'jquery',
        'modu',
        'domReady!'
    ], function($, modu) {

    console.log(modu.moduVar);

    modu.fromPhtml("This is output from ask.phtml");

});

</script>

Something like this.

Best Answer

You need to actually return your data, this works:

define([
    "jquery",
    "domReady!"
], function($) {
    "use strict";
    var modu = {};
    var moduVar = 'ModuVar test var';

    function fromPhtml(x) {
        console.log(x);
    }

    return modu = {
        moduVar: moduVar,
        fromPhtml: fromPhtml
    };
});

In your template/other Js file:

require([
    'jquery',
    'Magento_Catalog/js/modu',
    'domReady!'
], function($, modu) {
    console.log(modu.moduVar);
    modu.fromPhtml('This is output from ask.phtml');
});

Result

enter image description here

FYI I have changed the paths as I mocked this up quickly.