Class

Collection (utils)

@ckeditor/ckeditor5-utils/src/collection

class

Collections are ordered sets of objects. Items in the collection can be retrieved by their indexes in the collection (like in an array) or by their ids.

If an object without an id property is being added to the collection, the id property will be generated automatically. Note that the automatically generated id is unique only within this single collection instance.

By default an item in the collection is identified by its id property. The name of the identifier can be configured through the constructor of the collection.

Filtering

Properties

  • first

    Returns the first item from the collection or null when collection is empty.

  • last

    Returns the last item from the collection or null when collection is empty.

  • length : Number

    The number of items available in the collection.

  • _bindToCollection : Collection

    protected

    A collection instance this collection is bound to as a result of calling bindTo method.

  • _bindToExternalToInternalMap : WeakMap

    protected

    A helper mapping external items of a bound collection (bindTo) and actual items of this collection. It provides information necessary to properly remove items bound to another collection.

  • _bindToInternalToExternalMap : WeakMap

    protected

    A helper mapping items of this collection to external items of a bound collection (bindTo). It provides information necessary to manage the bindings, e.g. to avoid loops in two–way bindings.

  • _idProperty : String

    private

    The name of the property which is considered to identify an item.

  • _itemMap : Map

    private

    The internal map of items in the collection.

  • _items : Array.<Object>

    private

    The internal list of items in the collection.

  • _skippedIndexesFromExternal : Array

    private

    Stores indexes of skipped items from bound external collection.

Methods

  • constructor( [ initialItemsOrOptions ], [ options ] = { [options.idProperty] } )

    Creates a new Collection instance.

    You can provide an iterable of initial items the collection will be created with:

    const collection = new Collection( [ { id: 'John' }, { id: 'Mike' } ] );
    
    console.log( collection.get( 0 ) ); // -> { id: 'John' }
    console.log( collection.get( 1 ) ); // -> { id: 'Mike' }
    console.log( collection.get( 'Mike' ) ); // -> { id: 'Mike' }
    

    Or you can first create a collection and then add new items using the add method:

    const collection = new Collection();
    
    collection.add( { id: 'John' } );
    console.log( collection.get( 0 ) ); // -> { id: 'John' }
    

    Whatever option you choose, you can always pass a configuration object as the last argument of the constructor:

    const emptyCollection = new Collection( { idProperty: 'name' } );
    emptyCollection.add( { name: 'John' } );
    console.log( collection.get( 'John' ) ); // -> { name: 'John' }
    
    const nonEmptyCollection = new Collection( [ { name: 'John' } ], { idProperty: 'name' } );
    nonEmptyCollection.add( { name: 'George' } );
    console.log( collection.get( 'George' ) ); // -> { name: 'George' }
    console.log( collection.get( 'John' ) ); // -> { name: 'John' }

    Parameters

    [ initialItemsOrOptions ] : Iterable.<Object> | Object

    The initial items of the collection or the options object.

    [ options ] : Object

    The options object, when the first argument is an array of initial items.

    Properties
    [ options.idProperty ] : String

    The name of the property which is used to identify an item. Items that do not have such a property will be assigned one when added to the collection.

    Defaults to 'id'

    Defaults to {}

  • Symbol.iterator() → Iterable.<*>

    Iterable interface.

    Returns

    Iterable.<*>
  • add( item, [ index ] )

    Adds an item into the collection.

    If the item does not have an id, then it will be automatically generated and set on the item.

    Parameters

    item : Object
    [ index ] : Number

    The position of the item in the collection. The item is pushed to the collection when index not specified.

    Fires

  • addMany( item, [ index ] )

    Adds multiple items into the collection.

    Any item not containing an id will get an automatically generated one.

    Parameters

    item : Iterable.<Object>
    [ index ] : Number

    The position of the insertion. Items will be appended if no index is specified.

    Fires

  • bindTo( externalCollection ) → Object

    Binds and synchronizes the collection with another one.

    The binding can be a simple factory:

    class FactoryClass {
    	constructor( data ) {
    		this.label = data.label;
    	}
    }
    
    const source = new Collection( { idProperty: 'label' } );
    const target = new Collection();
    
    target.bindTo( source ).as( FactoryClass );
    
    source.add( { label: 'foo' } );
    source.add( { label: 'bar' } );
    
    console.log( target.length ); // 2
    console.log( target.get( 1 ).label ); // 'bar'
    
    source.remove( 0 );
    console.log( target.length ); // 1
    console.log( target.get( 0 ).label ); // 'bar'
    

    or the factory driven by a custom callback:

    class FooClass {
    	constructor( data ) {
    		this.label = data.label;
    	}
    }
    
    class BarClass {
    	constructor( data ) {
    		this.label = data.label;
    	}
    }
    
    const source = new Collection( { idProperty: 'label' } );
    const target = new Collection();
    
    target.bindTo( source ).using( ( item ) => {
    	if ( item.label == 'foo' ) {
    		return new FooClass( item );
    	} else {
    		return new BarClass( item );
    	}
    } );
    
    source.add( { label: 'foo' } );
    source.add( { label: 'bar' } );
    
    console.log( target.length ); // 2
    console.log( target.get( 0 ) instanceof FooClass ); // true
    console.log( target.get( 1 ) instanceof BarClass ); // true
    

    or the factory out of property name:

    const source = new Collection( { idProperty: 'label' } );
    const target = new Collection();
    
    target.bindTo( source ).using( 'label' );
    
    source.add( { label: { value: 'foo' } } );
    source.add( { label: { value: 'bar' } } );
    
    console.log( target.length ); // 2
    console.log( target.get( 0 ).value ); // 'foo'
    console.log( target.get( 1 ).value ); // 'bar'
    

    It's possible to skip specified items by returning falsy value:

    const source = new Collection();
    const target = new Collection();
    
    target.bindTo( source ).using( item => {
    	if ( item.hidden ) {
    		return null;
    	}
    
    	return item;
    } );
    
    source.add( { hidden: true } );
    source.add( { hidden: false } );
    
    console.log( source.length ); // 2
    console.log( target.length ); // 1
    

    Note: clear can be used to break the binding.

    Parameters

    externalCollection : Collection

    A collection to be bound.

    Returns

    Object
    CollectionBindToChain

    The binding chain object.

  • clear()

    Removes all items from the collection and destroys the binding created using bindTo.

    Fires

  • delegate( events ) → EmitterMixinDelegateChain

    mixed

    Delegates selected events to another Emitter. For instance:

    emitterA.delegate( 'eventX' ).to( emitterB );
    emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
    

    then eventX is delegated (fired by) emitterB and emitterC along with data:

    emitterA.fire( 'eventX', data );
    

    and eventY is delegated (fired by) emitterC along with data:

    emitterA.fire( 'eventY', data );

    Parameters

    events : String

    Event names that will be delegated to another emitter.

    Returns

    EmitterMixinDelegateChain
  • filter( callback, callback.item, callback.index, ctx ) → Array.<Object>

    Returns an array with items for which the callback returned a true value.

    Parameters

    callback : function
    callback.item : Object
    callback.index : Number
    ctx : Object

    Context in which the callback will be called.

    Returns

    Array.<Object>

    The array with matching items.

  • find( callback, callback.item, callback.index, ctx ) → Object

    Finds the first item in the collection for which the callback returns a true value.

    Parameters

    callback : function
    callback.item : Object
    callback.index : Number
    ctx : Object

    Context in which the callback will be called.

    Returns

    Object

    The item for which callback returned a true value.

  • fire( eventOrInfo, [ args ] ) → *

    mixed

    Fires an event, executing all callbacks registered for it.

    The first parameter passed to callbacks is an EventInfo object, followed by the optional args provided in the fire() method call.

    Parameters

    eventOrInfo : String | EventInfo

    The name of the event or EventInfo object if event is delegated.

    [ args ] : *

    Additional arguments to be passed to the callbacks.

    Returns

    *

    By default the method returns undefined. However, the return value can be changed by listeners through modification of the evt.return's property (the event info is the first param of every callback).

  • get( idOrIndex ) → Object | null

    Gets an item by its ID or index.

    Parameters

    idOrIndex : String | Number

    The item ID or index in the collection.

    Returns

    Object | null

    The requested item or null if such item does not exist.

  • getIndex( itemOrId ) → Number

    Gets an index of an item in the collection. When an item is not defined in the collection, the index will equal -1.

    Parameters

    itemOrId : Object | String

    The item or its ID in the collection.

    Returns

    Number

    The index of a given item.

  • has( itemOrId ) → Boolean

    Returns a Boolean indicating whether the collection contains an item.

    Parameters

    itemOrId : Object | String

    The item or its ID in the collection.

    Returns

    Boolean

    true if the collection contains the item, false otherwise.

  • listenTo( emitter, event, callback, [ options ] = { [options.priority] } )

    mixed

    Registers a callback function to be executed when an event is fired in a specific (emitter) object.

    Events can be grouped in namespaces using :. When namespaced event is fired, it additionally fires all callbacks for that namespace.

    // myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
    myEmitter.on( 'myGroup', genericCallback );
    myEmitter.on( 'myGroup:myEvent', specificCallback );
    
    // genericCallback is fired.
    myEmitter.fire( 'myGroup' );
    // both genericCallback and specificCallback are fired.
    myEmitter.fire( 'myGroup:myEvent' );
    // genericCallback is fired even though there are no callbacks for "foo".
    myEmitter.fire( 'myGroup:foo' );
    

    An event callback can stop the event and set the return value of the fire method.

    Parameters

    emitter : Emitter

    The object that fires the event.

    event : String

    The name of the event.

    callback : function

    The function to be called on event.

    [ options ] : Object

    Additional options.

    Properties
    [ options.priority ] : PriorityString | Number

    The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.

    Defaults to 'normal'

    Defaults to {}

  • map( callback, callback.item, callback.index, ctx ) → Array

    Executes the callback for each item in the collection and composes an array or values returned by this callback.

    Parameters

    callback : function
    callback.item : Object
    callback.index : Number
    ctx : Object

    Context in which the callback will be called.

    Returns

    Array

    The result of mapping.

  • off( event, callback )

    mixed

    Stops executing the callback on the given event. Shorthand for this.stopListening( this, event, callback ).

    Parameters

    event : String

    The name of the event.

    callback : function

    The function to stop being called.

  • on( event, callback, [ options ] = { [options.priority] } )

    mixed

    Registers a callback function to be executed when an event is fired.

    Shorthand for this.listenTo( this, event, callback, options ) (it makes the emitter listen on itself).

    Parameters

    event : String

    The name of the event.

    callback : function

    The function to be called on event.

    [ options ] : Object

    Additional options.

    Properties
    [ options.priority ] : PriorityString | Number

    The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.

    Defaults to 'normal'

    Defaults to {}

  • once( event, callback, [ options ] = { [options.priority] } )

    mixed

    Registers a callback function to be executed on the next time the event is fired only. This is similar to calling on followed by off in the callback.

    Parameters

    event : String

    The name of the event.

    callback : function

    The function to be called on event.

    [ options ] : Object

    Additional options.

    Properties
    [ options.priority ] : PriorityString | Number

    The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.

    Defaults to 'normal'

    Defaults to {}

  • remove( subject ) → Object

    Removes an item from the collection.

    Parameters

    subject : Object | Number | String

    The item to remove, its ID or index in the collection.

    Returns

    Object

    The removed item.

    Fires

  • stopDelegating( [ event ], [ emitter ] )

    mixed

    Stops delegating events. It can be used at different levels:

    • To stop delegating all events.
    • To stop delegating a specific event to all emitters.
    • To stop delegating a specific event to a specific emitter.

    Parameters

    [ event ] : String

    The name of the event to stop delegating. If omitted, stops it all delegations.

    [ emitter ] : Emitter

    (requires event) The object to stop delegating a particular event to. If omitted, stops delegation of event to all emitters.

  • stopListening( [ emitter ], [ event ], [ callback ] )

    mixed

    Stops listening for events. It can be used at different levels:

    • To stop listening to a specific callback.
    • To stop listening to a specific event.
    • To stop listening to all events fired by a specific object.
    • To stop listening to all events fired by all objects.

    Parameters

    [ emitter ] : Emitter

    The object to stop listening to. If omitted, stops it for all objects.

    [ event ] : String

    (Requires the emitter) The name of the event to stop listening to. If omitted, stops it for all events from emitter.

    [ callback ] : function

    (Requires the event) The function to be removed from the call list for the given event.

  • _addEventListener( event, callback, [ options ] = { [options.priority] } )

    protected mixed

    Adds callback to emitter for given event.

    Parameters

    event : String

    The name of the event.

    callback : function

    The function to be called on event.

    [ options ] : Object

    Additional options.

    Properties
    [ options.priority ] : PriorityString | Number

    The priority of this event callback. The higher the priority value the sooner the callback will be fired. Events having the same priority are called in the order they were added.

    Defaults to 'normal'

    Defaults to {}

  • _removeEventListener( event, callback )

    protected mixed

    Removes callback from emitter for given event.

    Parameters

    event : String

    The name of the event.

    callback : function

    The function to stop being called.

  • _setUpBindToBinding( factory )

    protected

    Finalizes and activates a binding initiated by {#bindTo}.

    Parameters

    factory : function

    A function which produces collection items.

  • _getItemIdBeforeAdding( item ) → String

    private

    Returns an unique id property for a given item.

    The method will generate new id and assign it to the item if it doesn't have any.

    Parameters

    item : Object

    Item to be added.

    Returns

    String
  • _remove( subject ) → Array

    private

    Core remove method implementation shared in other functions.

    In contrast this method does not fire the event-change event.

    Parameters

    subject : Object

    The item to remove, its id or index in the collection.

    Returns

    Array

    Returns an array with the removed item and its index.

    Fires

Events

  • add( eventInfo, item )

    Fired when an item is added to the collection.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    item : Object

    The added item.

  • change( eventInfo, added, removed, index )

    Fired when the collection was changed due to adding or removing items.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    added : Iterable.<Object>

    A list of added items.

    removed : Iterable.<Object>

    A list of removed items.

    index : Number

    An index where the addition or removal occurred.

  • remove( eventInfo, item, index )

    Fired when an item is removed from the collection.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    item : Object

    The removed item.

    index : Number

    Index from which item was removed.