OOjs/Events

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.

Model.js
function Model() {
	OO.EventEmitter.call( this );
	// State is just an example string attribute of the model; it could be anything.
	this.state = 'start';
}

OO.mixinClass( Model, OO.EventEmitter );

Model.prototype.getState = function () {
	return this.state;
}

Model.prototype.setState = function ( state ) {
	this.state = state;
	this.emit( 'changedState' );
}
View.js
function ViewButton( model ) {
	ViewButton.super.call ( this );
	this.model = model;
	// Listen for the model's 'changedState' events.
	this.model.connect( this, {
		changedState: 'updateStateLabel'
	} );
}

OO.inheritClass( ViewButton, OO.ui.ButtonWidget );

ViewButton.prototype.updateStateLabel = function () {
	// React to a change in the model.
	this.label = "State is: " + this.model.getState();
};

ViewButton.prototype.onClick = function () {
	// React to a user clicking this view, by changing the model.
	// This will end up updating the view label, but we don't do it directly here.
	this.model.setState( 'new state' );
};

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