Last active
August 29, 2015 14:05
-
-
Save elado/a6f5f1f8edade63a3b9d to your computer and use it in GitHub Desktop.
Angular Resource - Share all instances of a query across entire app
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
app = angular.module 'my-app', ['eo-cached-resource-action'] | |
app.factory 'Category', ($resource, cachedResourceAction) -> | |
Category = $resource "/categories/:id/:action", {id: '@id'}, { | |
query: { method: 'GET', cache: true, isArray: true } | |
} | |
Category.query = cachedResourceAction.wrapArrayAction(Category.query) | |
Category | |
# Usage as usual: | |
$scope.categories = Category.query() | |
# or | |
Category.query (categories) -> | |
$scope.categories = categories | |
# or | |
Category.query().$promise.then (categories) -> | |
$scope.categories = categories | |
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
app = angular.module 'eo-cached-resource-action', [] | |
app.factory 'cachedResourceAction', ($q) -> | |
arrayResult: -> | |
value = [] | |
value.$resolved = false | |
deferred = $q.defer() | |
value.$promise = deferred.promise | |
value.$$promise = deferred | |
value | |
resolveArrayResult: (value, items) -> | |
value.$resolved = true | |
value.length = 0 | |
Array::push.apply(value, items) | |
value.$$promise.resolve(value) | |
wrapArrayAction: (resourceActionFn) -> | |
_loading = false | |
_cachedValue = @arrayResult() | |
(callback) => | |
if _cachedValue.$resolved | |
_cachedValue.$$promise.resolve(_cachedValue) | |
else | |
_cachedValue.$promise.then(callback) if callback | |
if !_loading | |
# this happens only once | |
_loading = true | |
resourceActionFn (items) => | |
_loading = false | |
@resolveArrayResult(_cachedValue, items) | |
_cachedValue | |
# TODO: ability to invalidate cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment