Skip to content

Instantly share code, notes, and snippets.

@joshski
Forked from jcleveley-zz/patterns.js
Created July 8, 2011 14:16
Show Gist options
  • Save joshski/1071935 to your computer and use it in GitHub Desktop.
Save joshski/1071935 to your computer and use it in GitHub Desktop.
Javascript patterns
// namespace - single global variable for all news JS
var news = news || {};
// Example of a singleton as a revealing module
// When you only need one of something
news.preferences = (function (app, global) {
// Private variables
var persistent = true;
// Initialise Code
// Functions
var isPersistent = function () {
return persistent;
};
// Public interface
return {
isPersistent: isPersistent
};
}(news, this)); // <-- pass in app and global scope
// Singleton usage (Why isn't this code inside some module, is it just dangling?)
news.preferences.isPersistent();
// Example of constructor function
// When you need multiple instances of something
news.Gallery = (function (app, global) {
// Constructor function
var galleryConstructor = function Gallery(name, preferences) {
this.name = name;
this.shouldSaveChanges = preferences.isPersistent();
};
// Add instance functions to prototype
galleryConstructor.prototype.show = function () {
if (this.shouldSaveChanges) {
// depending on prefs but without the global access
}
};
// Return constructor function
return galleryConstructor;
}(news, this));
// Constructor function usage
var myGallery = new news.Gallery('My gallery', news.preferences);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment