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(){...} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A minor typo: L:23
Thanks for this code; works great 😄