Report an issue
Class

Model (engine/model)

@ckeditor/ckeditor5-engine/src/model/model

class

Editor's data model. Read about the model in the engine architecture guide.

Filtering

Properties

  • document : Document

    readonly

    Model's document.

  • markers : MarkerCollection

    readonly

    Model's marker collection.

  • schema : Schema

    readonly

    Model's schema.

  • _currentWriter : Writer

    private

    The last created and currently used writer instance.

  • _pendingChanges : Array.<Function>

    private

    All callbacks added by change or enqueueChange methods waiting to be executed.

Methods

  • applyOperation( operation )

    Decorated function to apply operations on the model.

    Parameters

    operation : Operation

    Operation to apply

  • bind( bindProperties ) → Object

    mixed

    Binds observable properties to another objects implementing Observable interface (like Model).

    Once bound, the observable will immediately share the current state of properties of the observable it is bound to and react to the changes to these properties in the future.

    Note: To release the binding use unbind.

    Using bind().to() chain:

    A.bind( 'a' ).to( B );
    A.bind( 'a' ).to( B, 'b' );
    A.bind( 'a', 'b' ).to( B, 'c', 'd' );
    A.bind( 'a' ).to( B, 'b', C, 'd', ( b, d ) => b + d );

    It is also possible to bind to the same property in a observables collection using bind().toMany() chain:

    A.bind( 'a' ).toMany( [ B, C, D ], 'x', ( a, b, c ) => a + b + c );
    A.bind( 'a' ).toMany( [ B, C, D ], 'x', ( ...x ) => x.every( x => x ) );

    Parameters

    bindProperties : String

    Observable properties that will be bound to another observable(s).

    Returns

    Object

    The bind chain with the to() and toMany() methods.

  • change( callback ) → *

    The change() method is the primary way of changing the model. You should use it to modify all document nodes (including detached nodes – i.e. nodes not added to the model document), the document's selection, and model markers.

    model.change( writer => {
        writer.insertText( 'foo', paragraph, 'end' );
    } );

    All changes inside the change block use the same Batch so they are combined into a single undo step.

    model.change( writer => {
        writer.insertText( 'foo', paragraph, 'end' ); // foo.
    
        model.change( writer => {
            writer.insertText( 'bar', paragraph, 'end' ); // foobar.
        } );
    
        writer.insertText( 'bom', paragraph, 'end' ); // foobarbom.
    } );

    The callback of the change() block is executed synchronously.

    You can also return a value from the change block.

    const img = model.change( writer => {
        return writer.createElement( 'img' );
    } );

    Parameters

    callback : function

    Callback function which may modify the model.

    Returns

    *

    Value returned by the callback.

  • decorate( methodName )

    mixed

    Turns the given methods of this object into event-based ones. This means that the new method will fire an event (named after the method) and the original action will be plugged as a listener to that event.

    This is a very simplified method decoration. Itself it doesn't change the behavior of a method (expect adding the event), but it allows to modify it later on by listening to the method's event.

    For example, in order to cancel the method execution one can stop the event:

    class Foo {
        constructor() {
            this.decorate( 'method' );
        }
    
        method() {
            console.log( 'called!' );
        }
    }
    
    const foo = new Foo();
    foo.on( 'method', ( evt ) => {
        evt.stop();
    }, { priority: 'high' } );
    
    foo.method(); // Nothing is logged.

    Note: we used a high priority listener here to execute this callback before the one which calls the original method (which used the default priority).

    It's also possible to change the return value:

    foo.on( 'method', ( evt ) => {
        evt.return = 'Foo!';
    } );
    
    foo.method(); // -> 'Foo'

    Finally, it's possible to access and modify the parameters:

    method( a, b ) {
        console.log( `${ a }, ${ b }`  );
    }
    
    // ...
    
    foo.on( 'method', ( evt, args ) => {
        args[ 0 ] = 3;
    
        console.log( args[ 1 ] ); // -> 2
    }, { priority: 'high' } );
    
    foo.method( 1, 2 ); // -> '3, 2'

    Parameters

    methodName : String

    Name of the method to decorate.

  • 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
  • deleteContent( selection, batch, [ options ] = { [options.leaveUnmerged], [options.doNotResetEntireContent] } )

    Deletes content of the selection and merge siblings. The resulting selection is always collapsed.

    Note: For the sake of predictability, the resulting selection should always be collapsed. In cases where a feature wants to modify deleting behavior so selection isn't collapsed (e.g. a table feature may want to keep row selection after pressing Backspace), then that behavior should be implemented in the view's listener. At the same time, the table feature will need to modify this method's behavior too, e.g. to "delete contents and then collapse the selection inside the last selected cell" or "delete the row and collapse selection somewhere near". That needs to be done in order to ensure that other features which use deleteContent() will work well with tables.

    Parameters

    selection : Selection | DocumentSelection

    Selection of which the content should be deleted.

    batch : Batch

    Batch to which the deltas will be added.

    [ options ] : Object
    Properties
    [ options.leaveUnmerged ] : Boolean

    Whether to merge elements after removing the content of the selection.

    For example <heading>x[x</heading><paragraph>y]y</paragraph> will become:

    • <heading>x^y</heading> with the option disabled (leaveUnmerged == false)
    • <heading>x^</heading><paragraph>y</paragraph> with enabled (leaveUnmerged == true).

    Note: object and limit elements will not be merged.

    Defaults to false

    [ options.doNotResetEntireContent ] : Boolean

    Whether to skip replacing the entire content with a paragraph when the entire content was selected.

    For example <heading>[x</heading><paragraph>y]</paragraph> will become:

    • <paragraph>^</paragraph> with the option disabled (doNotResetEntireContent == false)
    • <heading>^</heading> with enabled (doNotResetEntireContent == true)

    Defaults to false

    Fires

  • destroy()

    Removes all events listeners set by model instance and destroys Document.

  • enqueueChange( batchOrType, callback )

    The enqueueChange() method performs similar task as the change() method, with two major differences.

    First, the callback of enqueueChange() is executed when all other enqueued changes are done. It might be executed immediately if it is not nested in any other change block, but if it is nested in another (enqueue)change block, it will be delayed and executed after the outermost block.

    model.change( writer => {
        console.log( 1 );
    
        model.enqueueChange( writer => {
            console.log( 2 );
        } );
    
        console.log( 3 );
    } ); // Will log: 1, 3, 2.

    Second, it lets you define the Batch into which you want to add your changes. By default, a new batch is created. In the sample above, change and enqueueChange blocks use a different batch (and different Writer since each of them operates on the separate batch).

    When using the enqueueChange() block you can also add some changes to the batch you used before.

    model.enqueueChange( batch, writer => {
        writer.insertText( 'foo', paragraph, 'end' );
    } );

    The batch instance can be obtained from the writer.

    Parameters

    batchOrType : Batch | 'transparent' | 'default'

    Batch or batch type should be used in the callback. If not defined, a new batch will be created.

    callback : function

    Callback function which may modify the model.

  • 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).

  • getSelectedContent( selection ) → DocumentFragment

    Gets a clone of the selected content.

    For example, for the following selection:

    <p>x</p><quote><p>y</p><h>fir[st</h></quote><p>se]cond</p><p>z</p>

    It will return a document fragment with such a content:

    <quote><h>st</h></quote><p>se</p>

    Parameters

    selection : Selection | DocumentSelection

    The selection of which content will be returned.

    Returns

    DocumentFragment

    Fires

  • hasContent( rangeOrElement ) → Boolean

    Checks whether given range or element has any content.

    Content is any text node or element which is registered in schema.

    Parameters

    rangeOrElement : Range | Element

    Range or element to check.

    Returns

    Boolean
  • insertContent( content, selection )

    Inserts content into the editor (specified selection) as one would expect the paste functionality to work.

    Parameters

    content : DocumentFragment | Item

    The content to insert.

    selection : Selection | DocumentSelection

    Selection into which the content should be inserted.

    Fires

  • 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 {}

  • modifySelection( selection, [ options ] = { [options.direction], [options.unit] } )

    Modifies the selection. Currently, the supported modifications are:

    • Extending. The selection focus is moved in the specified options.direction with a step specified in options.unit. Possible values for unit are:
      • 'character' (default) - moves selection by one user-perceived character. In most cases this means moving by one character in String sense. However, unicode also defines "combing marks". These are special symbols, that combines with a symbol before it ("base character") to create one user-perceived character. For example, q̣̇ is a normal letter q with two "combining marks": upper dot (Ux0307) and lower dot (Ux0323). For most actions, i.e. extending selection by one position, it is correct to include both "base character" and all of it's "combining marks". That is why 'character' value is most natural and common method of modifying selection.
      • 'codePoint' - moves selection by one unicode code point. In contrary to, 'character' unit, this will insert selection between "base character" and "combining mark", because "combining marks" have their own unicode code points. However, for technical reasons, unicode code points with values above UxFFFF are represented in native String by two characters, called "surrogate pairs". Halves of "surrogate pairs" have a meaning only when placed next to each other. For example 𨭎 is represented in String by \uD862\uDF4E. Both \uD862 and \uDF4E do not have any meaning outside the pair (are rendered as ? when alone). Position between them would be incorrect. In this case, selection extension will include whole "surrogate pair".
      • 'word' - moves selection by a whole word.

    Note: if you extend a forward selection in a backward direction you will in fact shrink it.

    Parameters

    selection : Selection | DocumentSelection

    The selection to modify.

    [ options ] : Object
    Properties
    [ options.direction ] : 'forward' | 'backward'

    The direction in which the selection should be modified.

    Defaults to 'forward'

    [ options.unit ] : 'character' | 'codePoint' | 'word'

    The unit by which selection should be modified.

    Defaults to 'character'

    Fires

  • 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 {}

  • set( name, [ value ] )

    mixed

    Creates and sets the value of an observable property of this object. Such an property becomes a part of the state and is be observable.

    It accepts also a single object literal containing key/value pairs with properties to be set.

    This method throws the observable-set-cannot-override error if the observable instance already have a property with the given property name. This prevents from mistakenly overriding existing properties and methods, but means that foo.set( 'bar', 1 ) may be slightly slower than foo.bar = 1.

    Parameters

    name : String | Object

    The property's name or object with name=>value pairs.

    [ value ] : *

    The property's value (if name was passed in the first parameter).

  • 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.

  • transformDeltas( deltasA, deltasB, [ useContext ] ) → Object

    Transforms two sets of deltas by themselves. Returns both transformed sets.

    Parameters

    deltasA : Array.<Delta>

    Array with the first set of deltas to transform. These deltas are considered more important (than deltasB) when resolving conflicts.

    deltasB : Array.<Delta>

    Array with the second set of deltas to transform. These deltas are considered less important (than deltasA) when resolving conflicts.

    [ useContext ] : Boolean

    When set to true, transformation will store and use additional context information to guarantee more expected results. Should be used whenever deltas related to already applied deltas are transformed (for example when undoing changes).

    Defaults to false

    Returns

    Object
    Array.<Delta>

    return.deltasA The first set of deltas transformed by the second set of deltas.

    Array.<Delta>

    return.deltasB The second set of deltas transformed by the first set of deltas.

  • unbind( [ unbindProperties ] )

    mixed

    Removes the binding created with bind.

    A.unbind( 'a' );
    A.unbind();

    Parameters

    [ unbindProperties ] : String

    Observable properties to be unbound. All the bindings will be released if no properties provided.

  • _runPendingChanges() → Array.<*>

    private

    Common part of change and enqueueChange which calls callbacks and returns array of values returned by these callbacks.

    Returns

    Array.<*>

    Array of values returned by callbacks.

Events

  • _change( eventInfo, writer )

    protected

    Fired after leaving each enqueueChange block or outermost change block.

    Note: This is an internal event! Use event-change instead.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    writer : Writer

    Writer instance that has been used in the change block.

  • applyOperation( eventInfo, args )

    Fired every time any operation is applied on the model using applyOperation.

    Note that this event is suitable only for very specific use-cases. Use it if you need to listen to every single operation applied on the document. However, in most cases event-change should be used.

    A few callbacks are already added to this event by engine internal classes:

    • with highest priority operation is validated,
    • with normal priority operation is executed,
    • with low priority the Document updates its version,
    • with low priority LivePosition and LiveRange update themselves.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    args : Array

    Arguments of the applyOperation which is an array with a single element - applied operation.

  • change:{property}( eventInfo, name, value, oldValue )

    mixed

    Fired when a property changed value.

    observable.set( 'prop', 1 );
    
    observable.on( 'change:prop', ( evt, propertyName, newValue, oldValue ) => {
        console.log( `${ propertyName } has changed from ${ oldValue } to ${ newValue }` );
    } );
    
    observable.prop = 2; // -> 'prop has changed from 1 to 2'

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    name : String

    The property name.

    value : *

    The new property value.

    oldValue : *

    The previous property value.

  • deleteContent( eventInfo, args )

    Event fired when deleteContent method is called.

    The default action of that method is implemented as a listener to this event so it can be fully customized by the features.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    args : Array

    The arguments passed to the original method.

  • getSelectedContent( eventInfo, args )

    Event fired when getSelectedContent method is called.

    The default action of that method is implemented as a listener to this event so it can be fully customized by the features.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    args : Array

    The arguments passed to the original method.

  • insertContent( eventInfo, args )

    Event fired when insertContent method is called.

    The default action of that method is implemented as a listener to this event so it can be fully customized by the features.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    args : Array

    The arguments passed to the original method.

  • modifySelection( eventInfo, args )

    Event fired when modifySelection method is called.

    The default action of that method is implemented as a listener to this event so it can be fully customized by the features.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    args : Array

    The arguments passed to the original method.

  • set:{property}( eventInfo, name, value, oldValue )

    mixed

    Fired when a property value is going to be set but is not set yet (before the change event is fired).

    You can control the final value of the property by using the event's return property.

    observable.set( 'prop', 1 );
    
    observable.on( 'set:prop', ( evt, propertyName, newValue, oldValue ) => {
        console.log( `Value is going to be changed from ${ oldValue } to ${ newValue }` );
        console.log( `Current property value is ${ observable[ propertyName ] }` );
    
        // Let's override the value.
        evt.return = 3;
    } );
    
    observable.on( 'change:prop', ( evt, propertyName, newValue, oldValue ) => {
        console.log( `Value has changed from ${ oldValue } to ${ newValue }` );
    } );
    
    observable.prop = 2; // -> 'Value is going to be changed from 1 to 2'
                         // -> 'Current property value is 1'
                         // -> 'Value has changed from 1 to 3'

    Note: Event is fired even when the new value is the same as the old value.

    Parameters

    eventInfo : EventInfo

    An object containing information about the fired event.

    name : String

    The property name.

    value : *

    The new property value.

    oldValue : *

    The previous property value.