Search code examples
javascriptjquerywebpackwebpack-encorematerial-components-web

Can't access window["var_name"] with Webpack Encore


Based on the code below, I have a varaible mdcDialog, which is initialized with material-components-web (MDCDialog) library once page is loaded.

On form submit, default event is prevented and instead, ajaxSubmit() handle the form.
The response is a json object, from which I can find the variable response.modal.modal with it's string value mdcDialog.

But for one reason or another, console.info(window[response.modal.modal]); return undefined instead of the variable mdcDialog.
On the other hand, doing console.log(mdcDialog) output the variable as it should.

How can I access my variable mdcDialog from a string response if window isn't working?

app.js

/* --- VARS --- */
const page="#page";
let mdcDialog;

/* --- FUNCTIONS --- */
function ajaxSubmit(node) {
    $.ajax({
        type: node.attr("method"),
        url: node.attr("action"),
        enctype: "multipart/form-data",
        data: new FormData(node[0]),
        processData: false,
        contentType: false,
        cache: false
    }).done(function(response, status, xhr) {
        if(response !== false) {
            /** @var response.modal */
            if(typeof response.modal !== "undefined") {
                /** @var response.modal.action */
                /** @var response.modal.modal */
                /** @var response.modal.content */
                if(response.modal.action === "load") {
                    console.info(window[response.modal.modal]);
                }
            }
        }

    }).fail(function(request, status, error) {
        console.error(request);
        console.error(status);
        console.error(error);
    });
}

/* --- ACTIONS --- */
$(document).ready(function() {
    mdcDialog=new mdc.dialog.MDCDialog(document.querySelector("#dialog-level.mdc-dialog"));

    $(page).on("submit", ".ajs", function(e) {
        e.preventDefault();
        ajaxSubmit($(this));
    })
});

Solution

  • Variables defined with let or const have block scope, and even if they are defined in the outermost scope, they won't be defined globally and therefore will never be accessible through the global (window) object.

    To make them accessible that way, you have to use var, or to define them on the global object itself.

    let foo=1
    window.foo //undefined
    foo        //1
    
    var bar=2
    window.bar //2
    bar        //2
    
    window.baz=3
    window.baz //3
    baz        //3
    

    See this SO answer for more information