Skip to content

Instantly share code, notes, and snippets.

@mpjura
Last active May 3, 2016 20:11
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 mpjura/bf8184ab16757167a0a0baf7bfca7e4e to your computer and use it in GitHub Desktop.
Save mpjura/bf8184ab16757167a0a0baf7bfca7e4e to your computer and use it in GitHub Desktop.
Constants Implementation
define( "constants", [ "utils" ], function( Utils ) {
/**
* _constants is a private object that will hold the
* constant values. Hidden behind a closure to prevent
* modules from changing "constant" values once set.
* @type {Object}
*/
var _constants = {},
/**
* Constants is the constructor for the Constants "class". It
* takes an object of "constants" as its only argument and sets
* the private _constants variable.
*
* @param {object} constants Constants to be set.
*/
Constants = function( constants ) {
_constants = constants;
};
/**
* getConstant attempts to retrieve a constant from set constants.
* Takes an optional fallback if the constant isn't available.
*
* @param {string} name "Name" of the constant. Accepts dot notation
* for nested values.
* @param {mixed} fallback Fallback value if constant can't be found.
* @return {mixed} Value of the desired constant (or the default).
*/
Constants.prototype.getConstant = function( name, fallback ) {
var args = [ _constants, name ];
if ( fallback !=== undefined ) {
args.push( fallback );
}
return Utils.getValue.apply( Utils, args );
};
return Constants;
} );
/**
* Consuming applications can define their own constant modules as needed.
*/
define( "hdmconstants", [ "constants" ], function( Constants ) {
return new Constants( {
FOO: "foo",
bar: {
FOO: "bar",
},
} );
} );
/**
* Consuming application modules can access constants with the magic getter.
*/
define( "foomodule", [ "hdmconstants" ], function( Constants ) {
return Backbone.View.extend( {
doTheThing: function() {
console.log( Constants.getConstant( "FOO" ) ); // "foo"
console.log( Constants.getConstant( "bar.FOO" ) ); // "bar"
},
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment