Create a gist now

Instantly share code, notes, and snippets.

@ydaniv /shall.js
Last active Aug 29, 2015

What would you like to do?
A mix of pub/sub and Promises that allows decoupled transfer of control from one component to another.
/**
* Assuming an implementation of a pub/sub system that provides publish() and subscribe() functions.
* Also assuming a Promises A+ implementation.
*
* In this way a publisher that requires some unknown subscriber to either accept or decline can
* publish an event that will pass a deferred object to any subscribed component that can either
* resolve or reject the promise.
*
* A nice example is some action button that requires a modal confirm dialog to prompt the user to
* either accept or decline the action.
* This of course can be done by publishing an event back from dialog back to the action button,
* but by passing a deferred object behind the scenes we create a direct, yet loosely coupled,
* reverse connection between the subscriber and the publisher.
*
* The most straight forward benefit of this pattern is that there's no need for the 2 other events
* to publish and subscribe to, in the reverse direction.
* In the example above these would be the accept and decline events back from the dialog to the
* action button.
*/
// somewhere: some component is subscribing
subscribe('topic', function (deferred) {
if ( deferred.data && deferred.data.correct ) {
});
// somewhere else: some other component is publishing
var data = {
correct: true
};
shall('topic', data)
.then(function (value) {
// resolved
}, function (reason) {
// rejected
});
// where the implementation of shall() would be something along:
function shall (topic, data) {
return Promise(function (resolve, reject) {
publish(topic, {
resolve: resolve,
reject: reject,
data: data
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment