Skip to content

Instantly share code, notes, and snippets.

@jakobdamjensen
Last active December 27, 2017 01:02
Show Gist options
  • Save jakobdamjensen/c63f179023556ef68ac4 to your computer and use it in GitHub Desktop.
Save jakobdamjensen/c63f179023556ef68ac4 to your computer and use it in GitHub Desktop.
example of mixing pub-su
// 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;
};
var obervableObject = eventsMixin({});
var component1 = {
controller: function(){
observable.subscribe('myFancyEvent',function(e) {
});
observable.broadcast('myOtherEvent', 'data');
}
}
var component2 = {
controller: function(){
observable.subscribe('myOtherEvent',function(e) {
});
observable.broadcast('myFancyEvent', 'data');
}
}
@purefan
Copy link

purefan commented Dec 27, 2017

observable.subscribe

Where is observable defined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment