Skip to content

Instantly share code, notes, and snippets.

@webcss
Last active August 9, 2016 12:44
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save webcss/98fba43578c2954dd5cb to your computer and use it in GitHub Desktop.
Save webcss/98fba43578c2954dd5cb to your computer and use it in GitHub Desktop.
PubSub mixin using CustomEvents
// 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(){...}
@pelonpelon
Copy link

CustomEvent.initCustomEvent() has been deprecated.
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/initCustomEvent

@webcss
Copy link
Author

webcss commented May 2, 2015

It's just to implement custom events api for older browses

@barneycarroll
Copy link

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.

@pelonpelon
Copy link

Wasn't a recommendation for change. Just a heads-up.

@webcss
Copy link
Author

webcss commented May 2, 2015

Removed CustomEvent shim. Fixed a bug which prevented events from actually beeing removed on unload ☺️

@nickolasgregory
Copy link

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