Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- *** 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;
- }
- let index = entry.indexOf(item.index);
- if (index === -1) {
- continue;
- }
- entry.splice(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);
- }
- };
Add Comment
Please, Sign In to add comment