Open main menu

OO.EventEmitter is a mixin that allows event handlers to be attached, called when events occur, and detached.

Basic usageEdit

The simplest way to attach and detach event handlers is by using the on and off methods of every OOjs and OOUI object.

function onClick() { /* Handle click */ }

// Attach onClick to click event
obj.on( 'click', onClick );
// Detach onClick to click event
obj.off( 'click', onClick );

Using with objectsEdit

When working with methods, you can use the connect and disconnect methods. connect lets you wire up multiple events at once using less code, and disconnect knows how to unplug them all.

function View( model ) {
    // Properties
    this.model = model;

    // Events
    this.model.connect( this, {
        change: 'onChange',
        select: 'onSelect'
    } );
}

View.prototype.onChange = function () { /* Handle change */ };
View.prototype.onSelect = function ( from, to ) { /* Handle selection */ };
View.prototype.destroy = function () {
    // Detach all of this object's event handlers
    this.model.disconnect( this );
};

Emitting eventsEdit

Attached event handlers are called with arguments provided to the emit method.

Model.prototype.select = function ( from, to ) {
    this.selection = [ from, to ];
    // Call attached event handlers
    this.emit( 'select', from, to );
};

See alsoEdit