Skip to content

Instantly share code, notes, and snippets.

@codejets
Created March 19, 2016 20:21
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 codejets/d4604d6d6df7409ab1cd to your computer and use it in GitHub Desktop.
Save codejets/d4604d6d6df7409ab1cd to your computer and use it in GitHub Desktop.
module pattern
// Module Pattern
/*
In Simple terms, Module pattern is a collection of functions in a object literal.
*/
/*
We will make a simple service to store and retrive data from localStorage.
*/
(function() {
'use strict';
function authtoken() {
var storage = $window.localStorage;
var token = 'token';
var cachedToken;
// Works like a menu for all the APIs in this module
var service = {
setToken: setToken,
getToken: getToken,
removeToken: removeToken,
removeAll: removeAll,
authUser: authUser,
isAuthenticated: isAuthenticated,
};
return service;
function authUser(data) {
setToken('username', data.name);
setToken('token', data.token);
}
function setToken(key, token) {
cachedToken = token;
storage.setItem(key, token);
}
function removeToken(key) {
cachedToken = null;
storage.removeItem(key);
}
function removeAll () {
storage.clear();
}
function getToken(key) {
cachedToken = storage.getItem(key);
return cachedToken;
}
function isAuthenticated() {
return !!this.getToken(token);
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment