Bare Bones javascript Pub/Sub mechanism


class TalkingHead {
	constructor(){}
	yell( data ){
		console.warn('HEYYYYYY', data )
	}
	whisper( data ){
		console.log('PSSSSSSS', data )
	}
}

class MessageBroker {

	constructor(){
		this.subscribers = {}
	}

	publish( event, data ){
		if( !this.subscribers[ event ] ) return
	    this.subscribers[ event ].forEach( subscriberCallback => subscriberCallback( data ) )
	}

	subscribe( event, callback ){
		if( !this.subscribers[event] )  this.subscribers[event] = []
	    this.subscribers[event].push( callback )
	}

}

const broker = new MessageBroker()
const user = new TalkingHead()

broker.subscribe('yell', user.yell )
broker.subscribe('whisper', user.yell )

setTimeout(()=>{
	broker.publish('yell', {
		all: 'the',
		data: 'you',
		could: 'ever',
		want: document,
	})
}, 500)

setTimeout(()=>{
	broker.publish('whisper')
}, 1000)

oko
friend