Skip to content

Instantly share code, notes, and snippets.

@vbilopav
Last active February 19, 2019 14:26
Show Gist options
  • Save vbilopav/d5dc2a925db32774752af754b45bc55b to your computer and use it in GitHub Desktop.
Save vbilopav/d5dc2a925db32774752af754b45bc55b to your computer and use it in GitHub Desktop.
/*
*** Publish/Subscribe global events functions - implementation of pubsub pattern for loose coupled components ***
Usage:
* Publish global application event:
publish("unique event name / category / subcategory", arg1, arg2, arg3);
or
publish(["event1", "event2", "event3"], arg1, arg2, arg3);
* Subscribe to global application event:
(as many subscribtions as neccessary)
subscribe("unique event name", (arg1, arg2, arg3) => { console.log("Do something useful on 'unique event name'..."); });
or
subscribe(["event1", "event2", "event3"], () => { console.log("Do something useful on those three events ..."); });
* To unsubscribe from global application event:
(which may be necessary on componentWillUnmount because react components can't update state when component isn't mounted)
let ref = subscribe("unique event name", (arg1, arg2, arg3) => { });
unsubscribe("unique event name", ref);
unsubscribe will return true if event or events where unsubscribed
*/
const
_entries = {};
export const
subscribe = (name, handler) => {
const
doSub = n => {
let
entry = _entries[n];
if (!entry) {
entry = _entries[n] = [];
}
return _entries[n].push(handler) - 1;
};
if (name instanceof Array) {
let result = [];
for(let i of name) {
result.push({"name": i, index: doSub(i)});
}
return result;
} else {
return doSub(name);
}
};
export const
unsubscribe = (name, ref) => {
let
result = false;
if (ref instanceof Array === false) {
ref = [{"name": name, index: ref}];
}
for(let item of ref) {
let entry = _entries[item.name]
if (!entry) {
continue;
}
entry.splice(item.index, 1);
if (!result) {
result = true;
}
}
return result;
};
export const
publish = (name, ...args) => {
const
doPub = n => {
const
entry = _entries[n];
if (!entry) {
return;
}
entry.forEach(f => f.apply(this, args));
};
if (name instanceof Array) {
for(let i of name) {
doPub(i);
}
} else {
doPub(name);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment