undo3d-run-test
Version:
A collection of utilities for testing Undo3D, and apps built with Undo3D
44 lines (34 loc) • 1.53 kB
JavaScript
//// Receives and broadcasts events. Helps keep things loosely coupled.
//// CLASS
export default class Hub {
////
constructor () {
//// Define `handlerArrays` - an object where each key is an event-name,
//// and each value is an array of handlers.
this.handlerArrays = {}
}
//// Registers a new handler, under one or more event-names. Similar to
//// the DOM’s `addEventListener()`.
on (eventName, handler) {
const parts = eventName.split(' ')
if (1 < parts.length) { // go recursive for space-delimited event-names
parts.map( part => this.on(part, handler) )
} else { // create a handler-array if none currently exists
this.handlerArrays[eventName] = this.handlerArrays[eventName] || []
this.handlerArrays[eventName].push(handler)
}
}
//// Triggers the handlers for an event-name or sequence of event-names. The
//// event-name, along with all other arguments, will be passed as arguments
//// to each handler.
fire (eventNames, ...payload) {
eventNames = eventNames.split(' ').map( eventName => eventName.trim() )
for (const eventName of eventNames) {
const handlerArray = this.handlerArrays[eventName]
if (! handlerArray) continue // no such handler-array
handlerArray.map( //@TODO capture and return all results?
handler => handler.apply( null, [eventName].concat(payload) )
)
}
}
}