Skip to content

Instantly share code, notes, and snippets.

@mikehains
Created May 4, 2018 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehains/3b155a01bbf72975cdb62f17315135ed to your computer and use it in GitHub Desktop.
Save mikehains/3b155a01bbf72975cdb62f17315135ed to your computer and use it in GitHub Desktop.
Javascript module storing globals in an easy jQuery like way
<script type="text/javascript">
(function(){
// These are <<functions>> exposed on the object as properties.
var _publics = {
globals : _globals
};
/* ----------------------------------------------------------------
Setup. One Time (first time through) only
---------------------------------------------------------------- */
_globals.vars = {};
/* ----------------------------------------------------------------
Setting: concept.globals('test',5);
Multiple setting: concept.globals({test: 5, front: 17});
Reading: concept.globals('test');
Multiple reading: concept.globals()
---------------------------------------------------------------- */
function _globals() {
// No arguments at all, means we return the whole object
if (arguments.length === 0) {
return _globals.vars;
}
// First argument is an object
if (typeof arguments[0] === "object") {
// Empty object means existing values are retained
_globals.vars = $.extend({}, _globals.vars, arguments[0] || {});
}
// One argument - is seeking a value
if (arguments.length === 1) {
return _globals.vars[arguments[0]];
}
// Two arguments .... the first is property name, second is value
if (arguments.length > 1) {
_globals.vars[arguments[0]] = arguments[1];
}
}
/* ----------------------------------------------------------------------------
THE MAIN FUNCTION
---------------------------------------------------------------------------- */
function _main(in_obj) {
console.log('---------- OBJECT CALL -------------');
}
// make this available everywhere, at all times !
window.concept = _main;
// Add additional properties to the ui_dialog, so that we can call them using
// function-like calls eg ui_dialog.close()
// Uses ES6 method
Object.assign(window.concept, _publics);
})(jQuery);
function test() {
console.log('TEST 1: initial reading');
console.log(concept.globals());
console.log('TEST 2: setting single value');
concept.globals('test2','my test 2');
console.log(concept.globals());
console.log('TEST 3: multiple setting');
concept.globals({test2: 'still test 2', "test 3": "Foo"});
console.log(concept.globals());
console.log("TEST 4: single reading");
console.log(concept.globals('test 3'));
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment