Skip to content

Instantly share code, notes, and snippets.

@outbreak
Last active March 30, 2018 08:07
Show Gist options
  • Save outbreak/427af3425a18fab7a1678a7b21592f99 to your computer and use it in GitHub Desktop.
Save outbreak/427af3425a18fab7a1678a7b21592f99 to your computer and use it in GitHub Desktop.
Dispatcher pub/sub pattern
var Dispatcher = (function() {
var instance
var subscribers
var reset = function () {
subscribers = {}
}
var unsubscribe = function (type, handler, context) {
context = context || null
subscribers[type] = subscribers[type].filter(function (subscriber) {
return subscriber.handler !== handler && subscriber.context !== context
})
}
var subscribe = function (type, handler, context) {
context = context || null
if (!subscribers[type]) {
subscribers[type] = []
}
var subscriber = {
handler: handler,
context: context
}
subscribers[type] = subscribers[type].concat([subscriber])
return function () {
unsubscribe(type, handler, context)
}
}
var publish = function (type, data) {
subscribers[type].forEach(function (subscriber) {
subscriber.handler.call(subscriber.context, data)
})
}
var create = function () {
reset()
return Object.defineProperties({}, {
subscribe: {
value: subscribe
},
publish: {
value: publish
}
})
}
return function () {
if (!instance) {
instance = create()
}
return instance
}
})()
var dispatcher = Dispatcher()
var unsubscribe = dispatcher.subscribe('event.name', function (data) {
...
code
...
})
unsubscribe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment