Created
June 3, 2014 20:09
-
-
Save 8bitDesigner/c0ed753b93e80e56d49e 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
# In the class | |
class Model | |
fetch: (options = {}) -> | |
opts = _.extend({}, options) | |
_(opts).defaults | |
method: 'GET' | |
url: _.result(@, 'url') | |
cancellableHttpRequest(opts).then(_(@parse).bind(@)).then(_(@set).bind(@)) | |
# A helper method for allowing cancellable HTTP requests | |
cancellableHttpRequest = (opts) -> | |
dfd = $q.defer() | |
req = $http(opts) | |
# Wrap the request promise with our promise | |
req.then (res) -> dfd.resolve(res) | |
req.catch (res) -> dfd.reject(res) | |
dfd.promise.cancel = -> dfd.reject('cancelled') | |
return dfd.promise | |
# And usage in your app: | |
req = model.fetch(some: 'opts') | |
$scope.$on '$destroy', req.cancel() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment