Created
August 20, 2013 01:34
-
-
Save davidpp/6276159 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*global localStorage*/ | |
| /** | |
| * The Cacher Module with the service CacheLocal | |
| */ | |
| angular.module('Cacher', []). | |
| factory('CacheLocal', function($cacheFactory) { | |
| var cache = $cacheFactory('someCache', {}); | |
| var PREFIX = 'Cacher::'; | |
| cache.get = function(key) { | |
| console.log('get', key); | |
| var lruEntry = localStorage.getItem(PREFIX + key); | |
| if (!lruEntry) return; // Cache miss | |
| lruEntry = JSON.parse(lruEntry); | |
| console.log('hit', lruEntry); | |
| return lruEntry.data; // Cache hit | |
| }; | |
| cache.put = function(key, value) { | |
| if (typeof value.then === 'function') { | |
| value.then(function(value) { | |
| localStorage.setItem(PREFIX + key, JSON.stringify(value)); | |
| }); | |
| } else { | |
| localStorage.setItem(PREFIX + key, JSON.stringify(value)); | |
| } | |
| }; | |
| cache.remove = function(key) { | |
| localStorage.removeItem('Cacher::' + key); | |
| }; | |
| cache.removeAll = function() { | |
| localStorage.clear(); | |
| }; | |
| return cache; | |
| }); | |
| var app = angular.module('Test', ['Cacher']) | |
| .factory('AJAX', function($http, CacheLocal) { | |
| return { | |
| getWord: function(file) { | |
| var promise = $http.get(file, { | |
| cache: CacheLocal | |
| }).then(function(d) { | |
| return d.data; | |
| }); | |
| return promise; | |
| } | |
| }; | |
| }) | |
| .controller('MainCtrl', function($scope, AJAX) { | |
| $scope.obj = { | |
| filename: 'test.txt', | |
| result: '' | |
| }; | |
| $scope.refresh = function() { | |
| if (!this.obj.filename) return; | |
| this.obj.result = AJAX.getWord(this.obj.filename); | |
| }; | |
| $scope.refresh(); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment