Skip to content

Instantly share code, notes, and snippets.

@maplemap
Last active July 13, 2022 14:19
Show Gist options
  • Save maplemap/7343d959029c26e9ddab267134e7fd46 to your computer and use it in GitHub Desktop.
Save maplemap/7343d959029c26e9ddab267134e7fd46 to your computer and use it in GitHub Desktop.
Event Bus implementations
/*
* EventBus with multiply calling
*/
/*
* Based on Custom Element
*/
function EventBus() {
const bus = document.createElement('fakeelement');
this.subscribe = function(event, callback) {
bus.addEventListener(event, callback);
};
this.unsubscribe = function(event, callback) {
bus.removeEventListener(event, callback);
};
this.post = function(event, data) {
bus.dispatchEvent(new CustomEvent(event, {detail: data || {}}));
};
}
/*
* Based on Object
*/
function EventBus() {
const channels = {};
this.subscribe = function (channelName, listener) {
if (!channels[channelName]) {
channels[channelName] = [];
}
channels[channelName].push(listener);
};
this.unsubscribe = function(channelName) {
delete channels[channelName];
};
this.post = function (channelName, data) {
const channel = channels[channelName];
if (channel && channel.length > 0) {
channel.forEach(function (listener) {
listener(data);
});
}
};
}
/*
* EventBus with single calling
*/
function EventBus() {
const bus = {};
this.unsubscribe = function(event) {
delete bus[event];
};
this.subscribe = function(event, callback) {
bus[event] = callback;
};
this.post = function(event, data) {
if(bus[event]) {
bus[event](data);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment