Gets an item by its numeric zero-based index or key. The item's index may change after other items are added or removed. The item's key never changes, even after other items are added or removed.
Adds a new item to the collection. Arguments are (item, key, index). Returns a promise that resolves to the key of the added item.
This event is fired immediately after an item gets added. The arguments are (item, key, index).
This event is fired immediately after an item is added or removed. The event doesn't have any arguments.
Fetches all items of the collection from the server or fetches only one item by its index or key. Returns a promise that resolves to the array of the items or the requested item.
Removes an item from the collection. Returns a promise that resolves after the item is removed.
This event is fired immediately after an item gets removed. The arguments are (item, key, index).
The number of items in the collection as an observable property.
Creates a collection with some items removed. The created collection is read only and changes after the origin collection.
Creates a collection with customized .add and .remove methods.
Creates a collection with items mapped with the given function: The following is true at all times for any item:
items.map(fn)(i) == fn(items(i));
The created collection is read only and changes after the origin collection.
Aggregates the items in the collection into an observable property.
The key feature of this method is that it's like ko.computed observes the list of dependent properties and updates the aggregated value whenever any of the deps changes.
const values = Collection();
const product = values.reduce((val, prop) => val ? val * prop() : 0, 1);
const x = Property(); x.set(3);
const y = Property(); y.set(5);
const z = Property(); z.set(7);
values.add(x); // product() == 3
values.add(y); // product() == 3*5
values.add(z); // product() == 3*5*7
y.set(0); // product() == 0 and z is not even being observed
y.set(11); // product() == 3*11*7 and z is being observed again
A possible application is computing the number of online users:
const nOnline = persons.reduce((n, p) => n + (!!p.status() == "Online"), 0);
nOnline.changed(n => document.title = n + " people online");
This works as long as the computed value doesn't depend on some external source.
Created a collection with all items sorted. The given function is a predicate which says whether the order of two given items is correct; thus to do the basic sort use the following predicate:
items.sort((x, y) => x < y);
The created collection is read only and changes after the origin collection.
Tells the collection to keep its data up to date. This may result in creating a subscription on the server. If the items of the collection are needed only once, it's preferrable to use .get().
Gets all items of the collection as an array. The items cached in the collection may differ from items stored in the corresponding collection on the server.