我试图写第三方加载' Javascript,类似于Stripe,Disqus等。我们的想法是将变量作为配置访问,并能够与它进行交互。
所以,在我的应用程序的头部,我有2个脚本:
<script type="text/javascript" src="http:/domain/ks.js" async></script>
<script type="text/javascript">
Ks.setConfiguration("flow2");
</script>
ks.js
if (document.readyState === 'interactive') {
// The document has finished loading. We can now access the DOM elements.
Kb.setup();
}
var Kb = new function() {
// public
this.setConfiguration = function(key) {
var APP_KEY = key;
}
this.setup = function() {
checkConfiguration(APP_KEY);
internalFunction();
};
// private
var internalFunction = function() {
console.log("calling private function from namespace");
};
var checkConfiguration = function(key) {
// log message if key not set
console.log(key);
};
};
问题是我无法在主脚本中访问APP_KEY
变量。
我想要完成的是加载主脚本异步,设置配置,然后与配置项进行交互。
答案 0 :(得分:0)
尝试以下方法:
<script type="text/javascript" src="http:/domain/ks.js?callback=setConfig" async></script>
<script type="text/javascript">
function setConfig() {
Ks.setConfiguration("flow2");
}
</script>
加载脚本后应调用setConfig
答案 1 :(得分:0)
APP_KEY
function
是var _AAP_KEY; //private
this.setConfiguration = function(key) {
_AAP_KEY = key;
}
的本地人,这就是您无法访问的原因。
getter
您需要this.getConfiguration = function() {
return _AAP_KEY;
}
:
public class AddTestStepXmlParameterModel
{
public ParameterTypeEnum ParameterType { get; set; }
public string ParameterName { get; set; }
public string Description { get; set; }
[RequiredIf("BindingExists == false", ErrorMessage = "An XML File is required: Please Try again")]
[FileExtensions(Extensions = "xml", ErrorMessage = "Specify an XML file.")]
public HttpPostedFileBase XmlValue { get; set; }
public bool BindingExists { get; set; }
}
答案 2 :(得分:0)
你可以
添加this.getAppKey()
,但必须在APP_KEY
内定义var Kb = new function()
,而不是在闭包内。
由于var works的方式,它仍然有效,但为了清晰的代码,将其添加到&#34;类&#34;等级范围。
或者您可以将其声明为this.APP_KEY
并从<instance>.APP_KEY
访问它。
或者您可以将Kb()
变成一个模块,并在export it
APP_KEY
示例:
somefile.js
var Kb = new function() {
var APP_KEY = null; // this is defined on a higher scope
this.PUBLIC_APP_KEY = null; // with this you can call directly the key if you need to access it
// public
this.setConfiguration = function(key) {
APP_KEY = key;
this.PUBLIC_APP_KEY = key;
}
this.getKey = function() {
return APP_KEY;
}
this.setup = function() {
checkConfiguration(APP_KEY);
internalFunction();
};
// private
var internalFunction = function() {
console.log("calling private function from namespace");
};
var checkConfiguration = function(key) {
// log message if key not set
console.log(key);
};
};
现在在其他文件中你可以做到
if (document.readyState === 'interactive') {
var kb = Kb();
kb.setConfiguration(<somekey>);
console.log(kb.getKey()); // <somekey>
console.log(kb.PUBLIC_APP_KEY) // <somekey>
// The document has finished loading. We can now access the DOM elements.
Kb.setup();
}
或者,最后,你可以做这样的事情
// somefile.js
var key = "key";
// export it
exports.API_KEY = key;
和其他一些文件
import { API_KEY } from "somefile.js"