Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Last active December 26, 2015 19:19
Show Gist options
  • Save plukevdh/7200757 to your computer and use it in GitHub Desktop.
Save plukevdh/7200757 to your computer and use it in GitHub Desktop.
simple model with properties and delegation
class Collection
constructor: (items) ->
@all = if _.any(items, (item) => item instanceof @modelType)
items
else
(new @modelType(item) for item in items)
add: (item) ->
@all.push(item)
select: (key) ->
_.select @all, (item) =>
@_decodeFilter(item, key)
selectBy: (key, filters...) ->
_.select @all, (item) =>
_.include filters, @_decodeFilter(item, key)
_decodeFilter: (item, key) ->
func = item[key]
(if _.isFunction(func) then func.call(item) else func)
window.Collection = Collection
class Delegator
delegate: ->
methods = Array.prototype.slice.call(arguments)
delegate = methods.pop()
_.each methods, (method) =>
@[method] = _.bind(delegate[method], delegate)
class Model extends Delegator
constructor: (attrs) ->
@_setProperty(key, value) for key, value of attrs
_setProperty: (property, value) =>
@[property] = value
window.Model = Model
window.Delegator = Delegator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment