我正在尝试创建一个全局函数,我可以在.js
文件中的任何位置使用它。
我们有 50 多个 javascript 文件连接在一起,在每个文件中我希望能够在任何地方使用这个库。
本地化的.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
if (typeof Localized !== 'undefined') {
throw 'Localized" already in use';
}
root.Localized = factory();
}
}(this, function () {
var _strings,
_readyCallback,
_isReady = false,
_requestedStrings = false;
function ready( data ) {
_readyCallback = _readyCallback || function(){};
function domReady() {
// If the DOM isn't ready yet, repeat when it is
if ( document.readyState !== "complete" ) {
document.onreadystatechange = domReady;
return;
}
document.onreadystatechange = null;
_strings = data;
_isReady = true;
_readyCallback();
}
domReady();
}
// Get the current lang from the document's HTML element, which the
// server set when the page was first rendered. This saves us having
// to pass extra locale info around on the URL.
function getCurrentLang() {
var html = document.querySelector( "html" );
return html && html.lang ? html.lang : "en-US";
}
var Localized = {
get: function( key ) {
if ( !_strings ) {
console.error( "[goggles.webmaker.org] Error: string catalog not found." );
return "";
}
return ( _strings[ key ] || "" );
},
getCurrentLang: getCurrentLang,
// Localized strings are ready
ready: function( cb ) {
if ( !_requestedStrings ) {
_requestedStrings = true;
_readyCallback = cb;
function onload( data ) {
ready( data );
}
onload.error = console.log;
var xhr = new XMLHttpRequest();
xhr.open('GET', '/strings/' + getCurrentLang() + '?bust=' + Date.now(), false);
xhr.send(null);
if (xhr.status !== 200) {
err = new Error(id + ' HTTP status: ' + status);
err.xhr = xhr;
onload.error(err);
return;
}
onload(JSON.parse(xhr.responseText));
};
if ( _isReady ) {
_readyCallback();
}
},
isReady: function() {
return !!_isReady;
}
};
return Localized;
}));
所以我希望能够进入50 个文件中的任何一个并执行Localized.get("something");
但我什至没有在web 控制台Localized
中可用的对象。例如,如果你有你可以在 web 控制台中做,你可以在那里做任何事情。jQuery
$