OOjs/Events
< OOjs
OO.EventEmitter
is a mixin that allows event handlers to be attached, called when events occur, and detached.
Basic usage
editThe 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 objects
editWhen 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 events
editAttached event handlers are called with arguments provided to the emit
method.
Model.prototype.move = function ( x, y ) {
this.position = { x: x, y: y };
// Call attached event handlers
this.emit( 'position', { x: x, y: y } );
};
See also
edit- OO.EventEmitter API Documentation
- in any OOjs item's generated documentation, click "Events" to show its events
- OOUI Widgets synthesize meaningful events out of low-level DOM events.
- In OOUI, GroupElements can aggregate events from their items.
OOjs is maintained by the Editing department.
Get help:
|