Ali
Ali

Reputation: 10453

Create a global function in JavaScript

I'm trying to create a global function where I can use it anywhere inside a .js file.

We have more than 50 javascript files joined together and inside each files I want to be able to use this library anywhere.

Localized.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;
}));

So I want to be able to go into any of the 50 files and do Localized.get("something"); But then I don't even have the Localized object available in the web console. For example if you have jQuery you can do $ in the web console and you can do anything there.

Upvotes: 2

Views: 12979

Answers (2)

FeaturedSpace
FeaturedSpace

Reputation: 499

Have you ever looked at the Three.js global function? It's super easy to understand!

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.THREE = global.THREE || {})));
}(this, (function (exports) { 'use strict';

Upvotes: 2

Ali
Ali

Reputation: 10453

So it turns out that my javascript is globally defined and accessible everywhere within the file that is included and it can be call from the console as well except I have to initialize that by doing Localized.ready(function(){}); then I can get it to work.

So if anyone is looking to create their own global function and make it standard they can follow this way.

amdWeb.js is what I use as a standard to create global function.

Upvotes: 1

Related Questions