-
Notifications
You must be signed in to change notification settings - Fork 0
Collections
mike edited this page Apr 26, 2020
·
3 revisions
The persistence layer of Sirius
.
Instead of manipulating plain arrays, use Sirius.Collection
for saving models.
Features:
-
filters
-
indexes
-
parameterization
-
collection listeners
TodoList = new Sirius.Collection(Task) # parameterized by `Task` class
The same as in js arrays:
TodoList.push(myTask)
# or
TodoList.add(myTask)
# remove element
TodoList.remove(myTask)
# remove all elements
TodoList.clear()
Always when we create a new collection, we must pass the base class (child of Sirius.BaseModel
) for parameterization. And then if we try to add another class:
TodoList.add(123)
# Uncaught Error: Require `Task`, but given `Number`
TodoList.index(myTask) # int index or null
TodoList.first() # => first element or null
TodoList.last() # => last element or null
TodoList.all() # => return array of elements
TodoList.find('id', 123) # => return element or null
# in sql: `SELECT * FROM TodoList WHERE id=123 LIMIT 1`
TodoList.find_all('id', 123) # => return array of elements
# in sql: `SELECT * FROM TodoList WHERE id=123`
TodoList.takeFirst( (task) -> task.name() == "My Task" ) # => element or null
TodoList.filter( (task) -> task.completed()) # => array of elements
TodoList.each( (task) -> console.log(task.to_json()))
TodoList.map( (task) -> task.completed(true) ) # or .collect
TodoList.size() # => int number
TodoList.to_json() # => convert to json
TodoList.from_json(json) # => convert to collection
For quick access, use indexes.
# create a collection with `id` and `name` indexes
TodoList = new Sirius.Collection(Task, {index: ['id', 'name']}
Always add indexes for quick access.
Subscribe on collection changes (add or remove elements):
TodoList.subscribe('add', (task) -> ...your code... )
TodoList.subscribe('remove', (task) -> ...your code... )