Created
February 15, 2016 16:07
-
-
Save lgriffin/2031a6bcd1de467184a3 to your computer and use it in GitHub Desktop.
App Based Subscription model
This file contains 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 eventEmitter3 = require('eventemitter3'); | |
var EE = new eventEmitter3(); | |
EE.on('unsubscribe',function(appName){ | |
console.log("Unsubscribe request received for " + appName); | |
removeListener(appName); | |
}); | |
function addListener(appName) | |
{ | |
if(!EE.listeners(appName, true)) | |
{ | |
console.log("Adding a new listener"); | |
EE.on(appName, function(value){ | |
console.log("I fired for " + appName + " and my value is " + value); | |
}); | |
} | |
} | |
function removeListener(appName) | |
{ | |
EE.removeListener(appName); | |
} | |
console.log("Listener Count " + EE.listeners('app1').length); // should be 0 | |
EE.emit('app1'); | |
addListener('app1'); | |
console.log("Listener Count " + EE.listeners('app1').length); // should be 1 | |
EE.emit('app1',"Value 1"); | |
EE.emit('app1',"Value 2"); | |
EE.emit('app1',"Value 3"); | |
EE.emit('app1',"Value 4"); | |
addListener('app1'); // does nothing it is here already | |
addListener('app2'); // new listener!! | |
console.log("Listener Count " + EE.listeners('app1').length); // should still be 1 | |
EE.emit('app2',"Application2"); | |
EE.emit('app1',"Application1"); | |
EE.emit('unsubscribe', 'app1'); // no more App1 subscribtions | |
removeListener('app12344532'); // we can remove listeners that don't exist so no risk of crashing | |
console.log("Listener Count " + EE.listeners('app1').length); // should be 0 | |
console.log("Finished"); | |
EE.emit('app1',"Application1"); // nothing will fire here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment