Last active
August 29, 2015 14:09
-
-
Save phedinkus/f72c7dcfb417a5249be3 to your computer and use it in GitHub Desktop.
This file contains 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
angular.factory("Application", function($http){ | |
// We found in benchmarking that $resource was slower than bare $http | |
this.get = function(){ | |
return $http("url/to/application/data", {params: anythingNeeded}); | |
} | |
}); | |
angular.service("ApplicationCache", function($timeout, Application){ | |
var cache = [], | |
cacheMap = {}, | |
timerDelay = 1 * 60 * 1000; // 1 minute | |
// Return the cache array reference that you can bind to in a controller or directive. | |
// This adds complexity since you should NEVER break the reference by reassigning | |
// the cache variable. | |
this.all = function(){ | |
return cache; | |
}; | |
// Convenient lookup helper | |
this.find = function(id){ | |
var applicationIndex = cacheMap[id]; | |
return cache[applicationIndex]; | |
}; | |
var fetch = function(){ | |
Application.get() | |
.success(updateCache) | |
.error(someErrorHandlingFunctionOfYourChoosing) | |
}; | |
var updateCache = function(applicationData){ | |
var application, | |
availableLocation = cache.length; | |
for(var i = 0, len = applicationData.length; i < len; i++){ | |
application = applicationData[i]; | |
existingLocation = cacheMap[application.id]; | |
if (existingLocation !== undefined) { | |
updateCachedAttributes(application, existingLocation); | |
} else { | |
addNewApplication(application, availableLocation); | |
cacheMap[application.id] = availableLocation++; | |
} | |
} | |
}; | |
var updateCachedAttributes = function(applicationData, location){ | |
var application = cache[location]; | |
for(var attr in application){ | |
application[attr] = applicationData[attr]; | |
} | |
}; | |
var addNewApplication = function(applicationData, location){ | |
var application = new Application(applicationData); | |
cache[location] = application; | |
cacheMap[application.id] = location; | |
}; | |
$timeout(fetch, timerDelay); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment