Last active
December 27, 2017 01:02
-
-
Save jakobdamjensen/c63f179023556ef68ac4 to your computer and use it in GitHub Desktop.
example of mixing pub-su
This file contains hidden or 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; | |
}; | |
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'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Where is
observable
defined?