Skip to content

Instantly share code, notes, and snippets.

@prestonp
Created November 21, 2013 17:16
Show Gist options
  • Save prestonp/7585754 to your computer and use it in GitHub Desktop.
Save prestonp/7585754 to your computer and use it in GitHub Desktop.
A db enums module
// An example of a controller that would require the enums
var enums = require('./enums')(); // Get a singleton
/**
* Assuming a page isn't served before the asynchronous data is returned
* this should give us cached data
*/
var get = function(req, res) {
res.render('page', { tags: enums.getTags() });
}
var
models = require('../models')
, utils = require('../utils');
/**
* Database enumerations for various lists such
* tags, meal styles, etc. Implemented with the
* singleton pattern.
*
* http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript
*/
var enums = (function() {
// Store a reference to this singleton
var instance;
var init = function() {
// Private data
var tags;
models.Tag.find({}, function(err, results) {
tags = utils.invoke(results, 'toJSON');
});
// Public methods and variables
return {
getTags: function() {
return tags;
}
};
};
// Only instantiate once
return function() {
if(!instance) instance = init();
return instance;
};
})();
/**
* Expose module
*/
module.exports = enums;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment