Last active
August 9, 2016 12:44
-
-
Save webcss/98fba43578c2954dd5cb to your computer and use it in GitHub Desktop.
PubSub mixin using CustomEvents
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
// utilizes the browser eventsystem | |
// usefull in cases where you need communication between independent components | |
// registered events are automatically removed onunload with preserving any other onunload handler | |
var eventsMixin = function(target) { | |
var _subscriptions = []; | |
target.broadcast = function(type, payload) { | |
var ev = new CustomEvent(type, { | |
detail: payload, | |
bubbles: true, | |
cancelable: true | |
}); | |
document.dispatchEvent(ev); | |
}; | |
target.subscribe = function(type, callback, capture) { | |
_subscriptions.push([type, callback, capture]); | |
document.addEventListener(type, callback, capture || false); | |
}; | |
target.ignore = function(type, callback, capture) { | |
_subscriptions.splice(_subscriptions.indexOf([type, callback, capture]), 1); | |
document.removeEventListener(type, callback, capture || false); | |
}; | |
// save a reference to a possible present unload method | |
var _savedUnload = (target.onunload)? target.onunload : null; | |
target.onunload = function() { | |
while (_subscriptions.length) { | |
document.removeEventListener.apply(document, _subscriptions.pop()); | |
} | |
_savedUnload && _savedUnload(); | |
}; | |
return target; | |
}; | |
// usage: | |
var Customers = {}; | |
Customers.controller = function(args) { | |
var scope = eventsMixin(this); | |
scope.subscribe('myFancyEvent',function(e) { | |
// do somthing | |
}); | |
scope.broadcast('myOtherEvent', myData); | |
}; | |
Customers.view = function(){...} |
This works across the board right now. I think polyfilling the new standard would require breaking changes in end use signatures — a bit like the way components branch forces you to attach things to an object with some reserved keys as the first arg to a component.
Wasn't a recommendation for change. Just a heads-up.
Removed CustomEvent shim. Fixed a bug which prevented events from actually beeing removed on unload
A minor typo: L:23
target.ignore = function(type, callback, capture) {
_subcriptions.splice( ...
// ^ missing "s"
_subscriptions.splice( ...
Thanks for this code; works great 😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's just to implement custom events api for older browses