framework/js/lib/utils/evented.js

82 lines
1.8 KiB
JavaScript
Raw Normal View History

/**
* The `evented` mixin provides methods allowing an object to trigger events,
* running externally registered event handlers.
*/
2015-04-25 20:58:39 +08:00
export default {
/**
* Arrays of registered event handlers, grouped by the event name.
*
* @type {Object}
* @protected
*/
2015-04-25 20:58:39 +08:00
handlers: null,
/**
* Get all of the registered handlers for an event.
*
* @param {String} event The name of the event.
* @return {Array}
* @protected
2015-04-25 20:58:39 +08:00
*/
getHandlers(event) {
this.handlers = this.handlers || {};
this.handlers[event] = this.handlers[event] || [];
return this.handlers[event];
2015-04-25 20:58:39 +08:00
},
/**
* Trigger an event.
*
* @param {String} event The name of the event.
* @param {...*} args Arguments to pass to event handlers.
* @public
2015-04-25 20:58:39 +08:00
*/
trigger(event, ...args) {
this.getHandlers(event).forEach(handler => handler.apply(this, args));
2015-04-25 20:58:39 +08:00
},
/**
* Register an event handler.
*
* @param {String} event The name of the event.
* @param {function} handler The function to handle the event.
2015-04-25 20:58:39 +08:00
*/
on(event, handler) {
this.getHandlers(event).push(handler);
},
/**
* Register an event handler so that it will run only once, and then
* unregister itself.
*
* @param {String} event The name of the event.
* @param {function} handler The function to handle the event.
*/
one(event, handler) {
const wrapper = function() {
handler.apply(this, arguments);
this.off(event, wrapper);
};
this.getHandlers(event).push(wrapper);
},
2015-04-25 20:58:39 +08:00
/**
* Unregister an event handler.
*
* @param {String} event The name of the event.
* @param {function} handler The function that handles the event.
2015-04-25 20:58:39 +08:00
*/
off(event, handler) {
const handlers = this.getHandlers(event);
const index = handlers.indexOf(handler);
2015-04-25 20:58:39 +08:00
if (index !== -1) {
handlers.splice(index, 1);
}
}
}