質問

I have a javascript file that declares the variable below:

var page = page || {};

The above file is included in another javascript file that wants to make use of page variable. I can see that variable in intellisense when trying to type it.

But at runtime, I am getting error that :

page is not defined.

I am posting more elaborate code:

First file is page.js that has just one line

var page = page || {};

Second file uses the above variable:

/// <reference path="page.js" />

page.current = function () {
};

There is final third file:

/// <reference path="../pagescripts/page-current.js" />
define(function () {

var Agencies = function (app, datacontext, logger, config, router) {
     var myPage = page.current;
     //The above line throws error saying page is not defined.
});
};
役に立ちましたか?

解決

This pattern is commonly used when using the same namespace object across multiple files. By putting

var page = page || {}; 

at the top of each file that touches that namespace, you're guaranteed that page will point to the same object, and you can load them in any order, if your code permits.

// page1.js
var page = page || {};
page.doSomething = function() {};

// page2.js
var page = page || {}
page.doSomethingElse = function() {};

// page3.js
var page = page || {};
page.doThirdThing = function() {};

他のヒント

Make sure you load the javascript file that defines the variable before the file/script tag that uses it.

If you can not change the order of script file load for some reason, then you may use dom onready function to access this variable. As a rule of thumb, you should delay execution of your logic till dom is ready. e.g. in jQuery you can use

$(document).ready(function() {
// application init logic
// or start execution of functions
  if(page && page.whatever) {
      page.whatever();
  }
})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top