Skip to content

Instantly share code, notes, and snippets.

@lucasvo
Created August 24, 2012 07:09
Show Gist options
  • Save lucasvo/3446987 to your computer and use it in GitHub Desktop.
Save lucasvo/3446987 to your computer and use it in GitHub Desktop.
Querysets in Backbone
define ['jquery', 'underscore', 'backbone'], ($, _, Backbone) ->
# The queryset iterator is a helper that builds iterator functions that allow simple string matching such as:
# sample_iterator = (model) ->
# return model.get(key) == value
class QuerysetIterator
constructor: (expressions) ->
@expressions = expressions
iterator: (model) ->
for key, value in @expressions
if model.get('key') == value
return True
# The Queryset object is slighlty smarter than a list but not much. The big advantage is that it supports chainable filters.
# qs = new Queryset({models: collection.models });
# qs._filter(iterator).filter(iterator2)
#
# or you can use .filter for filtering with a certain attribute.
# qs.filter({name:'John Doe'})
class Queryset
constructor: (options) ->
@models = options['model']
if @models[0]
@collection = @models[0].collection
models: []
filter: (expressions) =>
qsiterator = new Queryset(expressions)
@_filter((model) ->
qsiterator.iterator(model)
)
_filter: (iterator, context) =>
new Queryset({models: _.filter(@models, iterator, context)})
each: (iterator, context) =>
_.each(@models, iterator, context)
Queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment