How to Wait Until text/x-magento-init Has Loaded the Options

javascriptjquerymagento2requirejs

enter image description here

It seems to me that text/x-magento-init returns options async:

<script type="text/x-magento-init">
    {
        "*": {
                "component": " <?php echo "test" ?> "

        }
    }
</script>

component.js

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

return {
    check : "3",        
    myVariable : "7",
    component: function(config, element) { 
        console.log(config) //OUTPUTS OK AFTER 3 SECONDS
        this.myVariable = config // replaces it with undefined when called in third.js       
    }
};

then in third.js where all info should be processed:

require([
        'jquery',        
        'component',
        'jquery/ui'
    ],
    function($,component){    

        $(document).ready(function(){
            component.component();
            console.log(component.myVariable) //undefined
            console.log(component.check)  //3

the right info is printed from component.js after being undefined.

also component.js is loaded by requirejs, in the sense that console.log(component.check) returns 3 as desired.

How to wait until config is loaded?

enter image description here

Question related to How to get url for static image file in Magento2 javascript files? but has progressed

Best Answer

I think the problem with what your trying to do is that a property defined dynamically within component.js will not be accessible from third.js.

As an alternative solution, you can pass whatever variables are needed directly to your 'third.js' file. You could use 'component.js' as a library of functions rather than as a middle man for passing data from the view.

In the template:

<script type="text/x-magento-init">
    {
        "*": {
            "third": {
                "var1" : "hello"
            }
        }
    }
</script>

third.js is defined like this:

define([
    'component'
], function (component) {
    'use strict';

    return function (config) {
        console.log(config); // will output the config object {var1: "hello"}
        component.foo(config.var1); // call function from component.js on data
    }
});

and component.js looks like this:

define([], function() {
    'use strict';
    return {
        foo: function (bar) {
            console.log(bar);
        }
    };
});
Related Topic