The last section for this chapter is about the OpenLayers' Collection class, ol.Collection. As mentioned, the Collection class is not a super class like Observable and Object, but it is an integral part of the relationship model. Many classes in OpenLayers make use of the Collection class to manage one-to-many relationships.
At its core, the Collection class is a JavaScript array with additional convenience methods. It also inherits directly from the Object class and inherits the functionality of both Observable and Object. This makes the Collection class extremely powerful and we will use it many times in the rest of this book.
A collection is created just like any other class, just use the new operator:
var collection = new ol.Collection();
The Collection constructor takes one optional argument, an array that is used to initially populate the collection with elements. The elements in the array can be of any type, but if you are using the collection with one of the OpenLayers API methods, the type of the values will typically be specified in the API documentation. For instance, the Map class constructor allows passing a collection of layers, interactions, controls, and overlays. In these cases, the contents of the collection must be instances of the correct type of an object. For instance, check the following code snippet:
var layer1 = new ol.layer.Tile({/*options */);
var layer2 = new ol.layer.Vector({/* options */});
var layerCollection = new ol.Collection([layer1, layer2]);
var map = new ol.Map({
layers: layerCollection
});A Collection class, inherited from the Object class, has one observable property, length. When a collection changes (elements are added or removed), its length property is updated. This means it also emits an event, change:length, when the length property is changed.
A Collection class also inherits the functionality of the Observable class (via Object class) and emits two other events—add and remove. Registered event handler functions of both events will receive a single argument, a CollectionEvent, that has an element property with the element that was added or removed.
The Collection class has the following methods (the ones from Object and Observable classes are not included in this list, but those methods are also available):