1

I've looked through and found many solutions on this topic - but none of them work within my specific implementation (that I can figure out). I'm new to javascript(and web dev in general) - so we can start with that. What i am trying to do is the following:

  1. I have a generic form for general CRUD maintenance of tables (like an admin page for updating reference data for the website).
  2. When this page (php) is executed a query parm is sent with the object name (aka object which has all the functions related to the table I'm performing CRUD actions on). For example ?division for the division table.
  3. I load the javascript file that holds the object definition into the web page by appending to the head.
  4. When the file is loaded - i want to execute the form initialization function for that object (which adds the specific fields to the form for the table)

My problem is that I have the object name (division) in a variable (objName) - and I can't find a way to actually reference anything within the object through using objName. I've found some answers specific to that - but I can't seem to get the to work in this context. I think it all has to do with finding the right way to reference the object at the window level through a variable name.

Here is my code (abbreviated for readability)

FILE: division.js

var division = {
    name: "Bobby",
    maintenanceForm : function() {
        console.log('maint form');
    }
}

HTML PAGE:

<head>
//  Some other stuff in here too...
<script type="text/javascript" src="/objects/division.js"></script>
</head>
<body>
// Some divs/forms/etc
</body>
<script>

    var objName = location.search.substr(1);
    var objFile = "/objects/" + objName + ".js";
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = objFile;
    scriptTag.addEventListener("load",objloaded);
    document.head.appendChild(scriptTag);

    function objloaded() {
        console.log(objName);      // prints our "division" so I know we have the value here.
        console.log(division);     // THIS WORKS
        console.log(this[objName]) // This comes back undefined which makes sense
                                    //  because "this" is this function and not the 
                                    // global page scope. 
                                    // So how do I reference the object in
                                    // the window scope through objName?         
    }

here is the console log.:

Geshode
  • 3,600
  • 6
  • 18
  • 32
WhenDingo
  • 11
  • 3

1 Answers1

0

I think that window[objName] will work.

fifn2
  • 382
  • 1
  • 6
  • 15