Skip to content
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:

  1. filters

  2. indexes

  3. parameterization

  4. collection listeners

how to create?

TodoList = new Sirius.Collection(Task) # parameterized by `Task` class

add & remove elements

The same as in js arrays:

TodoList.push(myTask)

# or 

TodoList.add(myTask)

# remove element

TodoList.remove(myTask)

# remove all elements

TodoList.clear()

parameterization

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`

access, filers, enumerators

get index of element

note: this method use compare from Sirius.BaseModel

TodoList.index(myTask) # int index or null

get first, last, or all elements

TodoList.first() # => first element or null
TodoList.last()  # => last element or null
TodoList.all()   # => return array of elements

find a model by key and value

TodoList.find('id', 123) # => return element or null

# in sql: `SELECT * FROM TodoList WHERE id=123 LIMIT 1`

find models by key and value

TodoList.find_all('id', 123) # => return array of elements

# in sql: `SELECT * FROM TodoList WHERE id=123`

get first by condition

TodoList.takeFirst( (task) -> task.name() == "My Task" ) # => element or null

filter collection

TodoList.filter( (task) -> task.completed()) # => array of elements

iterate

TodoList.each( (task) -> console.log(task.to_json())) 

modify collection (map, collect)

TodoList.map( (task) -> task.completed(true) ) # or .collect

actual size of collection

TodoList.size() # => int number

json

TodoList.to_json() # => convert to json 
TodoList.from_json(json) # => convert to collection

Indexes

For quick access, use indexes.

Note: indexes must be unique, otherwise you may get some surprises.

# create a collection with `id` and `name` indexes
TodoList = new Sirius.Collection(Task, {index: ['id', 'name']} 

Always add indexes for quick access.

Observable: event listeners

Subscribe on collection changes (add or remove elements):

TodoList.subscribe('add', (task) -> ...your code... )
TodoList.subscribe('remove', (task) -> ...your code... )