开发者

loading a JavaScript file with vars not set at load time

the post title may not explain fully, but here is what I am hoping to do: I have my JavaScript code in a separate file, and I have it arranged like so

var PK = {
    "vars" 开发者_如何学C: {
        "uris" : {
            "app1": "http://this/server/",
            "app2": "http://that/server/"
        },

        "something": {
            "objects": [],
            "obj1": { "url": PK.vars.uris.app1 },
            "obj2": { "url": PK.vars.uris.app2 }                                   
        }
    },

    "methods" : {
        "doThis" : function(a) {
            $.ajax({
                url: PK.vars.uris.app1,
                data: data,
                type: "GET",
                success: function(data) { .. do something .. }
            });     
        },

        "doThat" : function(a) {
            $.ajax({
                url: PK.vars.uris.app2,
                data: data,
                type: "GET",
                success: function(data) { .. do something else .. }
            });     
        },

        "init" : function(position) {
            if (position) { PK.methods.doThis();
            }
            else {
                PK.methods.doThat();
            }
        }
    }
};

and then, in my html, I have the following

$(document).ready(function() {
    PK.vars.uris.app1 = "[% app1 %]";
    PK.vars.uris.app2 = "[% app2 %]";
    PK.methods.init();
});

where the values of app1 and app2 are sent from the server based on a config file. Except, it doesn't work as expected, because, when the separate JavaScript loads, PK.vars.uris is not defined at that time. Of course, everything works beautifully if I have PK.vars.uris{} hardcoded.

How can I delay the evaluation of var PK until after the document has loaded and PK.vars.uris is available to be used in the JavaScript code?


Is the problem that you need to pass values into an initialiser?

How's this approach:

In your external file:

  function PK_Constructor(app1Uri, app2Uri) {
        this.vars = { "uris" : {
                    "app1" : app1Uri,
                    "app2" : app2Uri
            },
               "something": {
                    "objects": [],
                    "obj1": { "url": app1Uri },
                    "obj2": { "url": app1Uri }                                   
                 },
            };
       this.doThis = function(a) {
           $.ajax({
               url: this.vars.uris.app1,
               data: data,
               type: "GET",
               success: function(data) { .. do something .. }
           }); 
       // etc

    }

And in you HTML:

   // Ensuring PK has global scope
   var PK = undefined;

   $(document).ready(function() {
       PK = new PK_Constructor("[% app1 %]", "[% app2 %]");
   });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜