Created
December 2, 2014 21:21
-
-
Save 8bitDesigner/4d7f85f5627eb28f9196 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
app = angular.module('fs.collections') | |
app.factory 'BaseCollection', ($http, BaseModel) -> | |
class BaseCollection | |
model: BaseModel | |
currentlyFetching: false | |
constructor: (models, @opts) -> | |
@[key] = value for key, value of @opts | |
@models = [] | |
@length = 0 | |
@add models | |
url: -> | |
parse: (res) -> res.data | |
fetch: (options) -> | |
defaults = | |
method: 'GET' | |
url: _(@).result('url') | |
options = _.extend(defaults, options) | |
options.params = _.extend({}, options.params) if options.params | |
options.data = _.extend({}, options.data) if options.data | |
@currentlyFetching = true | |
req = $http(options).then(_.bind(@parse, @)).then (models) => | |
@reset() if options.reset | |
@add(models) | |
@ | |
req.finally => @currentlyFetching = false | |
return req | |
eq: (index) -> @models?[index] | |
get: (id) -> | |
_(@models).findWhere id: id | |
remove: (models) -> | |
isSingular = ! _(models).isArray() | |
models = [models] if isSingular | |
removed = [] | |
_(models).forEach (model) => | |
index = @indexOf(model) | |
return if index is -1 | |
removed.push model | |
@models.splice index, 1 | |
@length-- | |
if isSingular then removed[0] else removed | |
add: (models, options) -> | |
return unless models | |
options = _.extend({sort: true}, options) | |
isSingular = ! _(models).isArray() | |
models = if isSingular then [models] else models.slice() | |
added = [] | |
insertAt = if typeof options.at is 'undefined' then @length else options.at | |
models.forEach (model) => | |
model = @_prepareModel(model) | |
# Add this model unless we already have it in the collection | |
unless @get(model.id)? | |
added.push(model) | |
@length++ | |
@models.splice(insertAt, 0, model) | |
insertAt++ | |
@sort() if options.sort | |
return if isSingular then added[0] else added |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment