Created
January 13, 2019 15:12
-
-
Save imsarvesh/6f4285d4d5125cbbc5c33bfe330b7a45 to your computer and use it in GitHub Desktop.
Javascript Design Pattern : The Observer Pattern
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 eventManager = function(){ | |
var subscriptions = {}; | |
function subscribe(type, fn){ | |
if(!subscriptions[type]) { | |
subscriptions[type] = []; | |
} | |
if(subscriptions[type].indexOf(fn) == -1){ | |
subscriptions[type].push(fn); | |
} | |
} | |
function unsubscribe(type, fn){ | |
var listeners = subscriptions[type]; | |
if(!listeners) return; | |
var index = listeners.indexOf(fn); | |
if(index !== -1){ | |
listeners.splice(index, 1); | |
} | |
} | |
function publish(type, evntObj){ | |
var listeners = subscriptions[type]; | |
if(!listeners) return; | |
if(!evntObj.type){ | |
evntObj.type = type; | |
} | |
for(var i = 0; i < listeners.length; i++){ | |
listeners[i](evntObj); | |
} | |
} | |
return { | |
subscribe : subscribe, | |
unsubscribe : unsubscribe, | |
publish : publish | |
} | |
} | |
var evtMgr = eventManager() | |
evtMgr.subscribe('/hello', foo) | |
evtMgr.publish('/hello', {message : 'Hello'}) | |
evtMgr.unsubscribe('/hello', foo) | |
evtMgr.publish('/hello', {message : 'Hello'}) //no output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment