Created
February 28, 2020 10:25
-
-
Save faforty/fe5085551846af597b487142056f3c36 to your computer and use it in GitHub Desktop.
Dispatcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import DispatcherEvent from './DispatcherEvent' | |
export default class Dispatcher { | |
constructor () { | |
this.events = {} | |
} | |
dispatch (eventName, data) { | |
const event = this.events[eventName] | |
if (event) { | |
event.fire(data) | |
} | |
} | |
on (eventName, callback) { | |
let event = this.events[eventName] | |
if (!event) { | |
event = new DispatcherEvent(eventName) | |
this.events[eventName] = event | |
} | |
event.registerCallback(callback) | |
} | |
off (eventName, callback) { | |
const event = this.events[eventName] | |
if (event && event.callbacks.indexOf(callback) > -1) { | |
event.unregisterCallback(callback) | |
if (event.callbacks.length === 0) { | |
delete this.events[eventName] | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class DispatcherEvent { | |
constructor (eventName) { | |
this.eventName = eventName | |
this.callbacks = [] | |
} | |
registerCallback (callback) { | |
this.callbacks.push(callback) | |
} | |
unregisterCallback (callback) { | |
const index = this.callbacks.indexOf(callback) | |
if (index > -1) { | |
this.callbacks.splice(index, 1) | |
} | |
} | |
fire (data) { | |
const callbacks = this.callbacks.slice(0) | |
callbacks.forEach((callback) => { | |
callback(data) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment