Last active
November 13, 2019 18:40
-
-
Save trafficinc/724c3af4b81e02c0f9e23ef5915ad279 to your computer and use it in GitHub Desktop.
Event Bus Module
This file contains hidden or 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
var EventBus = (function(){ | |
"use strict"; | |
var subscriptions = {}; | |
var getNextUniqueId = getIdGenerator(); | |
var Bus = { | |
subscribe: function(eventType, callback) { | |
var id = getNextUniqueId(); | |
if(!subscriptions[eventType]) | |
subscriptions[eventType] = {}; | |
subscriptions[eventType][id] = callback; | |
return { | |
unsubscribe: function() { | |
delete subscriptions[eventType][id] | |
if(Object.keys(subscriptions[eventType]).length === 0) { | |
delete subscriptions[eventType]; | |
} | |
} | |
} | |
}, | |
publish: function(eventType, arg) { | |
if(!subscriptions[eventType]) | |
return | |
Object.keys(subscriptions[eventType]).forEach(function(key) { | |
subscriptions[eventType][key](arg); | |
}); | |
} | |
} | |
function getIdGenerator() { | |
var lastId = 0 | |
return function getNextUniqueId() { | |
lastId += 1 | |
return lastId | |
} | |
} | |
return { | |
subscribe: Bus.subscribe, | |
publish: Bus.publish | |
} | |
})(); | |
var subscription1 = EventBus.subscribe( | |
"print", function(message) { | |
console.log('printing: '+ message); | |
}); | |
var subscription2 = EventBus.subscribe( | |
"add", function(mynums) { | |
console.log(add(mynums[0],mynums[1])); | |
}); | |
// App Code | |
// single addition fx | |
function add(a,b) { | |
return a + b; | |
} | |
function doSomething() { | |
console.log("doSomething"); | |
console.log("Hello!"); | |
EventBus.publish("add", [10, 5]); | |
console.log("World"); | |
} | |
function doSomethingElse() { | |
console.log("doSomethingElse"); | |
console.log("Hi!"); | |
EventBus.publish("print", "Here is something to print, that is a little longer!"); | |
console.log("Bye"); | |
} | |
//Implementation | |
doSomething(); | |
doSomethingElse(); | |
//end of App | |
subscription1.unsubscribe(); | |
subscription2.unsubscribe(); | |
/* Output | |
"doSomething" | |
"Hello!" | |
15 | |
"World" | |
"doSomethingElse" | |
"Hi!" | |
"printing: Here is something to print, that is a little longer!" | |
"Bye" | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment